Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a timedelta to days, hours and minutes

I've got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I'm not fussed.

I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I'd ask here before busting out some nauseatingly simple (yet verbose) mathematics.

Mr Fooz raises a good point.

I'm dealing with "listings" (a bit like ebay listings) where each one has a duration. I'm trying to find the time left by doing when_added + duration - now

Am I right in saying that wouldn't account for DST? If not, what's the simplest way to add/subtract an hour?

like image 644
Oli Avatar asked Jan 22 '10 18:01

Oli


People also ask

How do I convert Timedelta to hours and minutes?

How to convert a timedelta to hours. We can follow the same logic to convert a timedelta to hours. Instead of dividing the total_seconds() by the number of seconds in a minute, or dividing the timedelta object by timedelta(minutes=1) , we do it for hour.

How do I convert Timedelta days to INT?

We can also convert the timedelta to an integer by dividing it by the timedelta of one day or by extracting its integer part using the astype() attribute.

How do you convert Timedelta to seconds?

To get the Total seconds in the duration from the Timedelta object, use the timedelta. total_seconds() method.


2 Answers

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 
like image 142
Alex Martelli Avatar answered Sep 29 '22 18:09

Alex Martelli


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 
like image 36
mberacochea Avatar answered Sep 29 '22 18:09

mberacochea