I'm a Python newbie (2 weeks) and I'm having trouble formatting a datetime.timedelta
object.
Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.
I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.
By the way, I'm using Google AppEngine
with Django Templates
for presentation.
If anyone can help or knows of a better way to resolve this, I would be very happy.
Thanks,
I used the
humanfriendly
python library to do this, it works very well.Available at https://pypi.org/project/humanfriendly/
You can just convert the timedelta to a string with str(). Here's an example:
He already has a timedelta object so why not use its built-in method total_seconds() to convert it to seconds, then use divmod() to get hours and minutes?
This works regardless if the time delta has even days or years.
I had a similar problem with the output of overtime calculation at work. The value should always show up in HH:MM, even when it is greater than one day and the value can get negative. I combined some of the shown solutions and maybe someone else find this solution useful. I realized that if the timedelta value is negative most of the shown solutions with the divmod method doesn't work out of the box:
timedelta to HH:MM string:
I personally use the
humanize
library for this:Of course, it doesn't give you exactly the answer you were looking for (which is, indeed,
str(timeA - timeB)
, but I have found that once you go beyond a few hours, the display becomes quickly unreadable.humanize
has support for much larger values that are human-readable, and is also well localized.It's inspired by Django's
contrib.humanize
module, apparently, so since you are using Django, you should probably use that.