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
There's no built-in formatter for
timedelta
objects, but it's pretty easy to do it yourself:Or, equivalently, if you're in Python 2.7+ or 3.2+:
Now you can print it however you want:
For example:
This will print:
If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:
Or you may want to write an
english_plural
function to do the's'
bits for you, instead of repeating yourself.From your comments, it sounds like you actually want to keep the days separate. That's even easier:
If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:
So, putting it together:
Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
For the timedelta:
But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.