how to calc the difference between two datetimes?

Robert Brewer fumanchu at amor.org
Sun May 8 21:11:57 EDT 2005


Stewart Midwinter wrote:
> After an hour of research, I'm more confused than ever. I don't know
> if I should use the time module, or the eGenix datetime module. Here's
> what I want to do:  I want to calculate the time difference (in
> seconds would be okay, or minutes), between two date-time strings.
> 
> so: something like this:
> time0 = "2005-05-06 23:03:44"
> time1 = "2005-05-07 03:03:44"
> 
> timedelta = someFunction(time0,time1)
> print 'time difference is %s seconds' % timedelta.
> 
> Which function should I use?

Use datetime.datetime objects and subtract one from the other:
http://docs.python.org/lib/datetime-datetime.html

import datetime
time0 = datetime.datetime(2005, 5, 6, 23, 3, 44)
time1 = datetime.datetime(2005, 5, 7, 3, 3, 44)

td = time1 - time0
print 'time difference is %s seconds' % td


The "td" object will be a datetime.timedelta object.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list