Datetime.timedelta

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue May 17 07:44:48 EDT 2011


En Tue, 17 May 2011 07:44:08 -0300, Tsolmon Narantsogt <mnts26 at gmail.com>  
escribió:

> I'm using datetime.timedelta and i have a problem
>
> delta = 1 day, 2:30:00
> hours = delta.days * 8
>
> how to add 8 + 2:30:00

Just operate with it as it were a number. The timedelta class implements  
all "sane" mathematical operations.

py> from datetime import *
py> def timedelta_from_dhms(days=0, hours=0, mins=0, secs=0):
...   return timedelta(days, hours*3600 + mins*60 + secs)
...
py> delta = timedelta_from_dhms(1, 2, 30)
py> delta
datetime.timedelta(1, 9000)
py> hours = delta.days * 8
py> delta + hours
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and  
'int'
py> hours = timedelta_from_dhms(0, delta.days * 8)
py> hours
datetime.timedelta(0, 28800)
py> delta + hours
datetime.timedelta(1, 37800)
py> def dhms_from_timedelta(td):
...   return td.days, td.seconds // 3600, (td.seconds % 3600) // 60,  
td.seconds % 60
...
py> dhms_from_timedelta(delta + hours)
(1, 10, 30, 0)

-- 
Gabriel Genellina




More information about the Python-list mailing list