[Tutor] time calc

Don Arnold darnold02 at sprynet.com
Wed Jun 23 06:32:59 EDT 2004


I was going to suggest using the the datetime module, but wasn't sure how
datetime.datetime() objects could be used without having the date specified.
I hadn't thought of using datetime.timedelta() objects all by themselves.
Very nice. Thanks, Magnus.

Don

-----Original Message-----
From: Magnus Lycka [mailto:magnus at thinkware.se] 
Sent: Tuesday, June 22, 2004 6:04 PM
To: Don Arnold; 'kevin parks'; tutor at python.org
Subject: Re: RE: [Tutor] time calc

Don Arnold wrote:
> Anyone know if there is a module that does time math

Certainly. Just read the standard library reference!
The module is called datetime. *Don't* reinvent this
wheel, regardless of what people might suggest! ;)

>>> import datetime
>>> TD = datetime.timedelta
>>> td1 = TD(hours=5,minutes=23)
>>> td2 = TD(hours=3,minutes=2)
>>> sum = td1+td2
>>> print sum
8:25:00
>>> td3 = TD(hours=23,minutes=2,seconds=13)
>>> sum += td3
>>> print sum
1 day, 7:27:13
>>> sum.days
1
>>> sum.seconds
26833
>>> now = datetime.datetime.now()
>>> then = now + sum
>>> print then
2004-06-24 06:47:42.732000
>>> then.date()
datetime.date(2004, 6, 24)
>>> then.time()
datetime.time(6, 47, 42, 732000)
>>> then.year
2004
>>> then.second
42
>>> then.strftime('%Y.%m.%d')
'2004.06.24'

Note that the time module has a strptime function:
   >>> import time
   >>> time.strptime('23:12','%M:%S')
   (1900, 1, 1, 0, 23, 12, 0, 1, -1)
but in general, datetime is much more useful.

I guess it would be nice with a datetime.timedelta.strptime
function, but I'm afraid we don't have that in the standard
library yet. You can use the components you have to turn your 
"MM:SS" strings into timedeltas though.

>>> def minsec(s):
	return (datetime.datetime(*time.strptime(s,'%M:%S')[:7])
		- datetime.datetime(1900,1,1,0))

>>> sum = TD(0)
>>> for s in "23:12 5:56 6:34 7:34".split():
	sum += minsec(s)

	
>>> print sum
0:43:16
>>> print sum.seconds
2596

(Or was that hours:minutes? Just change '%M:%S' to '%H:%M'
and (of course) rename the function as appropriate.)

-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus at thinkware.se




More information about the Tutor mailing list