简体   繁体   中英

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

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM