Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating Time in Python (datetime.timedelta?)

I am sure this is a nobrainer for a lot of you, but I find myself really confused with the whole datetime.timedelta thing. Essentially I timestamp something when I start startTime and then I timestamp the end of the process endTime and I am trying to get the difference in HH:MM:SS and am having no luck.

I get this error when I do print endTime - startTime:

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

Edited to include final result:

startTime = datetime.now()
<... my looping process ...>
endTime = datetime.now()
calcdTime = endTime - startTime
print str(calcdTime)[:-4]

This outputs to: H:MM:SS.MM (thus stripping the last 4 characters off the timedelta

like image 749
chow Avatar asked Aug 15 '11 03:08

chow


2 Answers

Use a datetime instead of a time. Subtracting one time from another is meaningless without a date; you can't just assume that they're on the same day and the left operand comes first.

like image 184
Wooble Avatar answered Oct 07 '22 01:10

Wooble


Depending on what you're doing with the information, you might want to just use time.time:

import time

starttime = time.time()

# do stuff

endtime = time.time()

elapsed = endtime - starttime
print elapsed

Which will give you the elapsed time in seconds. This is often more convenient than having a timedelta.

like image 37
agf Avatar answered Oct 07 '22 00:10

agf