[Tutor] Re: time arithmetic with 2.3 datetime module

Lee Harr missive at hotmail.com
Wed Feb 11 17:51:46 EST 2004


>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?


Make sure the values you pass to the datetime constructor
are numbers (not strings) ...


>>>from datetime import datetime
>>>date, start, end = '20040206', '10:30', '17:45'
>>>y,m,d = date[:4],date[4:6],date[6:]
>>>sh,sm = start.split(':')
>>>eh,em = end.split(':')
>>>sdt = datetime(y, m, d, sh, sm)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: an integer is required
>>>y, m, d = map(int, (y, m, d))
>>>y
2004
>>>sh, sm = map(int, (sh, sm))
>>>eh, em = map(int, (eh, em))
>>>sdt = datetime(y, m, d, sh, sm)
>>>sdt
datetime.datetime(2004, 2, 6, 10, 30)
>>>edt = datetime(y, m, d, eh, em)
>>>tdelta = edt - sdt
>>>tdelta
datetime.timedelta(0, 26100)
>>>tdelta.days
0
>>>tdelta.seconds
26100
>>>tdelta.seconds/60.0
435.0

_________________________________________________________________
Click here for a FREE online computer virus scan from McAfee. 
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963




More information about the Tutor mailing list