I get a start_date like this:
from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
I get output like this:
datetime.timedelta(0, 5, 41038)
How do I convert this into normal time like the following?
10 minutes, 1 hour like this
I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.
A
datetime.timedelta
corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).If you want to convert a
timedelta
into hours and minutes, you can use thetotal_seconds()
method to get the total number of seconds and then do some math:Just use strftime :)
Something like that:
After edited your question to format
timedelta
, you could use:I don't think it's a good idea to caculate yourself.
If you just want a pretty output, just covert it into
str
withstr()
function or directlyprint()
it.And if there's further usage of the hours and minutes, you can parse it to
datetime
object usedatetime.strptime()
(and extract the time part withdatetime.time()
mehtod), for example:There is no need for custom helper functions if all we need is to print the string of the form
[D day[s], ][H]H:MM:SS[.UUUUUU]
. timedelta object supportsstr()
operation that will do this. It works even in Python 2.6.Another alternative for this (older) question:
The above is a good way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1.) Anyway, the real work is being done by
time.strftime("%H:%M:%S", time.gmtime(36901))
which does work on the output ofgmtime()
.And, that's it! (NOTE: Here's a link to format specifiers for
time.strftime()
. ...)