alwbtc
alwbtc

Reputation: 29445

Python convert timedeltas into hours in string format

I have a timedelta object which is 3457 hours

timedelta(hours=3457)

I want to represent it in "HH:MM" format, which is "3457:00"

I do:

from datetime import datetime
hours = timedelta(hours=3457)
hours_string =  time.strftime("%H:%M", time.gmtime(hours.seconds))
print hours_string

"01:00"

How can I get "3457:00"?

Upvotes: 2

Views: 517

Answers (2)

martineau
martineau

Reputation: 123423

As the timedelta documentation notes, only days, seconds and microseconds are stored internally -- which means you'll have to manually convert them to the units you want (hours and minutes). Here's one way to do that:

from datetime import timedelta

d = timedelta(hours=3457, minutes=42)
wholehours, seconds = divmod(d.seconds, 60*60)
wholeminutes = seconds//60
deltahours = d.days*24 + wholehours
print('{:d}:{:02d}'.format(deltahours, wholeminutes))
# 3457:42

Here's a simpler alternative that produces the same result:

def deltatime_hours_mins(dt, sep=':'):
    secs = int(dt.total_seconds())
    return '{:d}{}{:02d}'.format(secs//3600, sep, secs//60 % 60)

print(deltatime_hours_mins(d))

Upvotes: 0

Lennart Regebro
Lennart Regebro

Reputation: 172209

Please note that 3457:00 is a nonsensical format. The "hour-colon-minutes" format is used in dates and times, and the hour then can't reasonably be any higher than 23. A more reasonable format is: 3457h 0m.

You can get it like this:

from datetime import timedelta

delta = timedelta(hours=3457)
minutes, seconds = divmod(delta.seconds, 60)
hours, minutes = divmod(minutes, 60)
hours += delta.days * 24

print '%sh %sm' % (hours, minutes)

Of course, an easier way is this:

from datetime import timedelta

delta = timedelta(hours=3457)
print delta

But that will give you "144 days, 1:00:00", which is a sane format, but not what you want.

Upvotes: 5

Related Questions