Oli - 5 months ago 62

Python Question

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?

Answer

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 "nauseating simple mathematics", e.g.:

```
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
```