[Tutor] time arithmetic with 2.3 datetime module
Karl Pflästerer
sigurd at 12move.de
Wed Feb 11 17:24:03 EST 2004
On 11 Feb 2004, Jeff Kowalczyk <- jtk at yahoo.com wrote:
> no tutorials on the new functionality. Every effort I make with timedelta
> or time arithmetic eventually goes awry with TypeError: unsupported type
> for timedelta seconds component: datetime.time
> I have a simple timecard input of strings:
> date, start, end = '20040206', '10:30', '17:45'
> After I parse out the date string: y,m,d = d[:4],d[4:6],d[6:]
> I want to make two times from the 24h time strings, combining with the
> shared parsed date if necessary, and return the difference in floating
> point (e.g. 7.25). Can anyone suggest the most expedient way to do this?
You could do it like that
>>> import datetime as dt
>>> date, start, end = '20040206', '10:30', '17:45'
>>> d, start, end = '20040206', '10:30', '17:45'
>>> y,m,d = d[:4],d[4:6],d[6:]
>>> starthr, startmin = map(int,start.split(':'))
>>> endhr, endmin = map(int,end.split(':'))
>>> d1 = dt.datetime(int(y), int(m), int(d), starthr, startmin)
>>> d2 = dt.datetime(int(y), int(m), int(d), endhr, endmin)
>>> delta = d2 - d1
>>> delta
datetime.timedelta(0, 26100)
>>> delta.seconds
26100
>>>
Now you just need a function to convert the seconds in a format you
like.
E.g. like that:
>>> def secs_to_float (s):
... divs = [60, 60, 24, 365]
... res = []
... for div in divs:
... s, r = divmod(s, div)
... res.append(r)
... res[1] = res[1] / 60.0
... res[0] = res[0] / 3600.0
... res.reverse()
... return res
...
>>> secs_to_float(delta.seconds)
[0, 7, 0.25, 0.0]
>>>
Above should be combined in one ore two functions.
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list