Convert a timedelta to days, hours and minutes
days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60
As for DST, I think the best thing is to convert both datetime
objects to seconds. This way the system calculates DST for you.
>>> m13 = datetime(2010, 3, 13, 8, 0, 0) # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0) # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple()) # difference in seconds
82800.0
>>> _/3600 # convert to hours
23.0
This is a bit more compact, you get the hours, minutes and seconds in two lines.
days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# If you want to take into account fractions of a second
seconds += td.microseconds / 1e6
If you have a datetime.timedelta
value td
, td.days
already gives you the "days" you want. timedelta
values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
For all coming along and searching for an implementation:
The above posts are related to datetime.timedelta, which is sadly not having properties for hours and seconds. So far it was not mentioned, that there is a package, which is having these. You can find it here:
- Check the source: https://github.com/andrewp-as-is/timedelta.py
- Available via pip: https://pypi.org/project/timedelta/
Example - Calculation:
>>> import timedelta
>>> td = timedelta.Timedelta(days=2, hours=2)
# init from datetime.timedelta
>>> td = timedelta.Timedelta(datetime1 - datetime2)
Example - Properties:
>>> td = timedelta.Timedelta(days=2, hours=2)
>>> td.total.seconds
180000
>>> td.total.minutes
3000
>>> td.total.hours
50
>>> td.total.days
2
I hope this could help someone...