Format timedelta to string - python

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.

You can just convert the timedelta to a string with str(). Here's an example:
import datetime
start = datetime.datetime(2009,2,10,14,00)
end = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00

As you know, you can get the total_seconds from a timedelta object by accessing the .seconds attribute.
Python provides the builtin function divmod() which allows for:
s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40
or you can convert to hours and remainder by using a combination of modulo and subtraction:
# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40

>>> str(datetime.timedelta(hours=10.56))
10:33:36
>>> td = datetime.timedelta(hours=10.505) # any timedelta object
>>> ':'.join(str(td).split(':')[:2])
10:30
Passing the timedelta object to the str() function calls the same formatting code used if we simply type print td. Since you don't want the seconds, we can split the string by colons (3 parts) and put it back together with only the first 2 parts.

def td_format(td_object):
seconds = int(td_object.total_seconds())
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', 60),
('second', 1)
]
strings=[]
for period_name, period_seconds in periods:
if seconds > period_seconds:
period_value , seconds = divmod(seconds, period_seconds)
has_s = 's' if period_value > 1 else ''
strings.append("%s %s%s" % (period_value, period_name, has_s))
return ", ".join(strings)

I personally use the humanize library for this:
>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'
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.

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?
hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)
This works regardless if the time delta has even days or years.

Here is a general purpose function for converting either a timedelta object or a regular number (in the form of seconds or minutes, etc.) to a nicely formatted string. I took mpounsett's fantastic answer on a duplicate question, made it a bit more flexible, improved readibility, and added documentation.
You will find that it is the most flexible answer here so far since it allows you to:
Customize the string format on the fly instead of it being hard-coded.
Leave out certain time intervals without a problem (see examples below).
Function:
from string import Formatter
from datetime import timedelta
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = int(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = int(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = int(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
Demo:
>>> td = timedelta(days=2, hours=3, minutes=5, seconds=8, microseconds=340)
>>> print strfdelta(td)
02d 03h 05m 08s
>>> print strfdelta(td, '{D}d {H}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{D:2}d {H:2}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{H}h {S}s')
51h 308s
>>> print strfdelta(12304, inputtype='s')
00d 03h 25m 04s
>>> print strfdelta(620, '{H}:{M:02}', 'm')
10:20
>>> print strfdelta(49, '{D}d {H}h', 'h')
2d 1h

I know that this is an old answered question, but I use datetime.utcfromtimestamp() for this. It takes the number of seconds and returns a datetime that can be formatted like any other datetime.
duration = datetime.utcfromtimestamp(end - begin)
print duration.strftime('%H:%M')
As long as you stay in the legal ranges for the time parts this should work, i.e. it doesn't return 1234:35 as hours are <= 23.

I would seriously consider the Occam's Razor approach here:
td = str(timedelta).split('.')[0]
This returns a string without the microseconds
If you want to regenerate the datetime.timedelta object, just do this:
h,m,s = re.split(':', td)
new_delta = datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s))
2 years in, I love this language!

maybe:
>>> import datetime
>>> dt0 = datetime.datetime(1,1,1)
>>> td = datetime.timedelta(minutes=34, hours=12, seconds=56)
>>> (dt0+td).strftime('%X')
'12:34:56'
>>> (dt0+td).strftime('%M:%S')
'34:56'
>>> (dt0+td).strftime('%H:%M')
'12:34'
>>>

I used the humanfriendly python library to do this, it works very well.
import humanfriendly
from datetime import timedelta
delta = timedelta(seconds = 321)
humanfriendly.format_timespan(delta)
'5 minutes and 21 seconds'
Available at https://pypi.org/project/humanfriendly/

Questioner wants a nicer format than the typical:
>>> import datetime
>>> datetime.timedelta(seconds=41000)
datetime.timedelta(0, 41000)
>>> str(datetime.timedelta(seconds=41000))
'11:23:20'
>>> str(datetime.timedelta(seconds=4102.33))
'1:08:22.330000'
>>> str(datetime.timedelta(seconds=413302.33))
'4 days, 18:48:22.330000'
So, really there's two formats, one where days are 0 and it's left out, and another where there's text "n days, h:m:s". But, the seconds may have fractions, and there's no leading zeroes in the printouts, so columns are messy.
Here's my routine, if you like it:
def printNiceTimeDelta(stime, etime):
delay = datetime.timedelta(seconds=(etime - stime))
if (delay.days > 0):
out = str(delay).replace(" days, ", ":")
else:
out = "0:" + str(delay)
outAr = out.split(':')
outAr = ["%02d" % (int(float(x))) for x in outAr]
out = ":".join(outAr)
return out
this returns output as dd:hh:mm:ss format:
00:00:00:15
00:00:00:19
02:01:31:40
02:01:32:22
I did think about adding years to this, but this is left as an exercise for the reader, since the output is safe at over 1 year:
>>> str(datetime.timedelta(seconds=99999999))
'1157 days, 9:46:39'

My datetime.timedelta objects went greater than a day. So here is a further problem. All the discussion above assumes less than a day. A timedelta is actually a tuple of days, seconds and microseconds. The above discussion should use td.seconds as joe did, but if you have days it is NOT included in the seconds value.
I am getting a span of time between 2 datetimes and printing days and hours.
span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)

I have a function:
def period(delta, pattern):
d = {'d': delta.days}
d['h'], rem = divmod(delta.seconds, 3600)
d['m'], d['s'] = divmod(rem, 60)
return pattern.format(**d)
Examples:
>>> td = timedelta(seconds=123456789)
>>> period(td, "{d} days {h}:{m}:{s}")
'1428 days 21:33:9'
>>> period(td, "{h} hours, {m} minutes and {s} seconds, {d} days")
'21 hours, 33 minutes and 9 seconds, 1428 days'

Following Joe's example value above, I'd use the modulus arithmetic operator, thusly:
td = datetime.timedelta(hours=10.56)
td_str = "%d:%d" % (td.seconds/3600, td.seconds%3600/60)
Note that integer division in Python rounds down by default; if you want to be more explicit, use math.floor() or math.ceil() as appropriate.

One liner. Since timedeltas do not offer datetime's strftime, bring the timedelta back to a datetime, and use stftime.
This can not only achieve the OP's requested format Hours:Minutes, now you can leverage the full formatting power of datetime's strftime, should your requirements change to another representation.
import datetime
td = datetime.timedelta(hours=2, minutes=10, seconds=5)
print(td)
print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))
Output:
2:10:05
02:10
This also solves the annoyance that timedeltas are formatted into strings as H:MM:SS rather than HH:MM:SS, which lead me to this problem, and the solution I've shared.

import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))

def seconds_to_time_left_string(total_seconds):
s = int(total_seconds)
years = s // 31104000
if years > 1:
return '%d years' % years
s = s - (years * 31104000)
months = s // 2592000
if years == 1:
r = 'one year'
if months > 0:
r += ' and %d months' % months
return r
if months > 1:
return '%d months' % months
s = s - (months * 2592000)
days = s // 86400
if months == 1:
r = 'one month'
if days > 0:
r += ' and %d days' % days
return r
if days > 1:
return '%d days' % days
s = s - (days * 86400)
hours = s // 3600
if days == 1:
r = 'one day'
if hours > 0:
r += ' and %d hours' % hours
return r
s = s - (hours * 3600)
minutes = s // 60
seconds = s - (minutes * 60)
if hours >= 6:
return '%d hours' % hours
if hours >= 1:
r = '%d hours' % hours
if hours == 1:
r = 'one hour'
if minutes > 0:
r += ' and %d minutes' % minutes
return r
if minutes == 1:
r = 'one minute'
if seconds > 0:
r += ' and %d seconds' % seconds
return r
if minutes == 0:
return '%d seconds' % seconds
if seconds == 0:
return '%d minutes' % minutes
return '%d minutes and %d seconds' % (minutes, seconds)
for i in range(10):
print pow(8, i), seconds_to_time_left_string(pow(8, i))
Output:
1 1 seconds
8 8 seconds
64 one minute and 4 seconds
512 8 minutes and 32 seconds
4096 one hour and 8 minutes
32768 9 hours
262144 3 days
2097152 24 days
16777216 6 months
134217728 4 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:
def td2HHMMstr(td):
'''Convert timedelta objects to a HH:MM string with (+/-) sign'''
if td < datetime.timedelta(seconds=0):
sign='-'
td = -td
else:
sign = ''
tdhours, rem = divmod(td.total_seconds(), 3600)
tdminutes, rem = divmod(rem, 60)
tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
return tdstr
timedelta to HH:MM string:
td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
'1:54'
td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
'51:02'
td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
'-3:02'
td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
'-843:02'

from django.utils.translation import ngettext
def localize_timedelta(delta):
ret = []
num_years = int(delta.days / 365)
if num_years > 0:
delta -= timedelta(days=num_years * 365)
ret.append(ngettext('%d year', '%d years', num_years) % num_years)
if delta.days > 0:
ret.append(ngettext('%d day', '%d days', delta.days) % delta.days)
num_hours = int(delta.seconds / 3600)
if num_hours > 0:
delta -= timedelta(hours=num_hours)
ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours)
num_minutes = int(delta.seconds / 60)
if num_minutes > 0:
ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes)
return ' '.join(ret)
This will produce:
>>> from datetime import timedelta
>>> localize_timedelta(timedelta(days=3660, minutes=500))
'10 years 10 days 8 hours 20 minutes'

A straight forward template filter for this problem. The built-in function int() never rounds up. F-Strings (i.e. f'') require python 3.6.
#app_template_filter()
def diffTime(end, start):
diff = (end - start).total_seconds()
d = int(diff / 86400)
h = int((diff - (d * 86400)) / 3600)
m = int((diff - (d * 86400 + h * 3600)) / 60)
s = int((diff - (d * 86400 + h * 3600 + m *60)))
if d > 0:
fdiff = f'{d}d {h}h {m}m {s}s'
elif h > 0:
fdiff = f'{h}h {m}m {s}s'
elif m > 0:
fdiff = f'{m}m {s}s'
else:
fdiff = f'{s}s'
return fdiff

If you happen to have IPython in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time cell magic. I like the format it produces for short durations:
>>> from IPython.core.magics.execution import _format_time
>>>
>>> for v in range(-9, 10, 2):
... dt = 1.25 * 10**v
... print(_format_time(dt))
1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s

I continued from MarredCheese's answer and added year, month, millicesond and microsecond
all numbers are formatted to integer except for second, thus the fraction of a second can be customized.
#kfmfe04 asked for fraction of a second so I posted this solution
In the main there are some examples.
from string import Formatter
from datetime import timedelta
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02.0f}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02.0f}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02.0f}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02.0f}' --> ' 5d 8:04:02'
'{H}h {S:.0f}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = tdelta.total_seconds()
elif inputtype in ['s', 'seconds']:
remainder = float(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = float(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = float(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = float(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = float(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('Y','m','W', 'D', 'H', 'M', 'S', 'mS', 'µS')
constants = {'Y':86400*365.24,'m': 86400*30.44 ,'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1, 'mS': 1/pow(10,3) , 'µS':1/pow(10,6)}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
Quotient, remainder = divmod(remainder, constants[field])
values[field] = int(Quotient) if field != 'S' else Quotient + remainder
return f.format(fmt, **values)
if __name__ == "__main__":
td = timedelta(days=717, hours=3, minutes=5, seconds=8, microseconds=3549)
print(strfdelta(td,'{Y} years {m} months {W} weeks {D} days {H:02}:{M:02}:{S:02}'))
print(strfdelta(td,'{m} months {W} weeks {D} days {H:02}:{M:02}:{S:02.4f}'))
td = timedelta( seconds=8, microseconds=8549)
print(strfdelta(td,'{S} seconds {mS} milliseconds {µS} microseconds'))
print(strfdelta(td,'{S:.0f} seconds {mS} milliseconds {µS} microseconds'))
print(strfdelta(pow(10,7),inputtype='s'))
Output:
1 years 11 months 2 weeks 3 days 01:09:56.00354900211096
23 months 2 weeks 3 days 00:12:20.0035
8.008549 seconds 8 milliseconds 549 microseconds
8 seconds 8 milliseconds 549 microseconds
115d 17h 46m 40s

Here's a function to stringify timedelta.total_seconds(). It works in python 2 and 3.
def strf_interval(seconds):
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
return '{} {} {} {}'.format(
"" if int(days) == 0 else str(int(days)) + ' days',
"" if int(hours) == 0 else str(int(hours)) + ' hours',
"" if int(minutes) == 0 else str(int(minutes)) + ' mins',
"" if int(seconds) == 0 else str(int(seconds)) + ' secs'
)
Example output:
>>> print(strf_interval(1))
1 secs
>>> print(strf_interval(100))
1 mins 40 secs
>>> print(strf_interval(1000))
16 mins 40 secs
>>> print(strf_interval(10000))
2 hours 46 mins 40 secs
>>> print(strf_interval(100000))
1 days 3 hours 46 mins 40 secs

timedelta to string, use for print running time info.
def strfdelta_round(tdelta, round_period='second'):
"""timedelta to string, use for measure running time
attend period from days downto smaller period, round to minimum period
omit zero value period
"""
period_names = ('day', 'hour', 'minute', 'second', 'millisecond')
if round_period not in period_names:
raise Exception(f'round_period "{round_period}" invalid, should be one of {",".join(period_names)}')
period_seconds = (86400, 3600, 60, 1, 1/pow(10,3))
period_desc = ('days', 'hours', 'mins', 'secs', 'msecs')
round_i = period_names.index(round_period)
s = ''
remainder = tdelta.total_seconds()
for i in range(len(period_names)):
q, remainder = divmod(remainder, period_seconds[i])
if int(q)>0:
if not len(s)==0:
s += ' '
s += f'{q:.0f} {period_desc[i]}'
if i==round_i:
break
if i==round_i+1:
s += f'{remainder} {period_desc[round_i]}'
break
return s
e.g. auto omit zero leading period:
>>> td = timedelta(days=0, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'second')
'2 hours 5 mins 8 secs'
or omit middle zero period:
>>> td = timedelta(days=2, hours=0, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'millisecond')
'2 days 5 mins 8 secs 3 msecs'
or round to minutes, omit below minutes:
>>> td = timedelta(days=1, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'minute')
'1 days 2 hours 5 mins'

Please check this function - it converts timedelta object into string 'HH:MM:SS'
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)

If you already have a timedelta obj then just convert that obj into string. Remove the last 3 characters of the string and print. This will truncate the seconds part and print the rest of it in the format Hours:Minutes.
t = str(timedeltaobj)
print t[:-3]

I wanted to do this so wrote a simple function. It works great for me and is quite versatile (supports years to microseconds, and any granularity level, e.g. you can pick between '2 days, 4 hours, 48 minutes' and '2 days, 4 hours' and '2 days, 4.8 hours', etc.
def pretty_print_timedelta(t, max_components=None, max_decimal_places=2):
'''
Print a pretty string for a timedelta.
For example datetime.timedelta(days=2, seconds=17280) will be printed as '2 days, 4 hours, 48 minutes'. Setting max_components to e.g. 1 will change this to '2.2 days', where the
number of decimal points can also be set.
'''
time_scales = [timedelta(days=365), timedelta(days=1), timedelta(hours=1), timedelta(minutes=1), timedelta(seconds=1), timedelta(microseconds=1000), timedelta(microseconds=1)]
time_scale_names_dict = {timedelta(days=365): 'year',
timedelta(days=1): 'day',
timedelta(hours=1): 'hour',
timedelta(minutes=1): 'minute',
timedelta(seconds=1): 'second',
timedelta(microseconds=1000): 'millisecond',
timedelta(microseconds=1): 'microsecond'}
count = 0
txt = ''
first = True
for scale in time_scales:
if t >= scale:
count += 1
if count == max_components:
n = t / scale
else:
n = int(t / scale)
t -= n*scale
n_txt = str(round(n, max_decimal_places))
if n_txt[-2:]=='.0': n_txt = n_txt[:-2]
txt += '{}{} {}{}'.format('' if first else ', ', n_txt, time_scale_names_dict[scale], 's' if n>1 else '', )
if first:
first = False
if len(txt) == 0:
txt = 'none'
return txt

I had the same problem and I am using pandas Timedeltas, didn't want to bring in additional dependencies (another answer mentions humanfriendly) so I wrote this small function to print out only the relevant information:
def format_timedelta(td: pd.Timedelta) -> str:
if pd.isnull(td):
return str(td)
else:
c = td.components._asdict()
return ", ".join(f"{n} {unit}" for unit, n in c.items() if n)
For example, pd.Timedelta(hours=3, seconds=12) would print as 3 hours, 12 seconds.

I suggest the following method so that we can utilize the standard formatting function, pandas.Timestamp.strftime!
from pandas import Timestamp, Timedelta
(Timedelta("2 hours 30 min") + Timestamp("00:00:00")).strftime("%H:%M")

Related

Converting seconds to minutes and hours and writing to a CSV file [duplicate]

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.
Is there an easy way to convert the seconds to this format in Python?
You can use datetime.timedelta function:
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
And then use string formatting to convert the result into your desired output:
print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime() requires.
Note: Truncates after 23:59:59
Using datetime:
With the ':0>8' format:
from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Without the ':0>8' format:
"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Using time:
from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit:
https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan
The following set worked for me.
def sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
A bit off topic answer but maybe useful to someone
def time_format(seconds: int) -> str:
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d}m {:02d}s'.format(m, s)
elif s > 0:
return '{:02d}s'.format(s)
return '-'
Results in:
print(time_format(25*60*60 + 125))
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35))
>>> 17H 00m 35s
print(time_format(3500))
>>> 58m 20s
print(time_format(21))
>>> 21s
This is how I got it.
def sec2time(sec, n_msec=3):
''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
if hasattr(sec,'__len__'):
return [sec2time(s) for s in sec]
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if n_msec > 0:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
else:
pattern = r'%02d:%02d:%02d'
if d == 0:
return pattern % (h, m, s)
return ('%d days, ' + pattern) % (d, h, m, s)
Some examples:
$ sec2time(10, 3)
Out: '00:00:10.000'
$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'
$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'
$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']
hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)
minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)
similarly, seconds (s) by remainder of hour and minutes calculation.
Rest is just string formatting!
def hms(seconds):
h = seconds // 3600
m = seconds % 3600 // 60
s = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(hms(7500)) # Should print 02h05m00s
If you need to get datetime.time value, you can use this trick:
my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
You cannot add timedelta to time, but can add it to datetime.
UPD: Yet another variation of the same technique:
my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.
dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.
from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
int(rt.hours), int(rt.minutes), int(rt.seconds)))
Prints
40.0
01:30:40
Here is a way that I always use: (no matter how inefficient it is)
seconds = 19346
def zeroes (num):
if num < 10: num = "0" + num
return num
def return_hms(second, apply_zeroes):
sec = second % 60
min_ = second // 60 % 60
hrs = second // 3600
if apply_zeroes > 0:
sec = zeroes(sec)
min_ = zeroes(min_)
if apply_zeroes > 1:
hrs = zeroes(hrs)
return "{}:{}:{}".format(hrs, min_, sec)
print(return_hms(seconds, 1))
RESULT:
5:22:26
Syntax of return_hms() function
The return_hms() function is used like this:
The first variable (second) is the amount of seconds you want to convert into h:m:s.
The second variable (apply_zeroes) is formatting:
0 or less: Apply no zeroes whatsoever
1: Apply zeroes to minutes and seconds when they're below 10.
2 or more: Apply zeroes to any value (including hours) when they're below 10.
Here is a simple program that reads the current time and converts it to a time of day in hours, minutes, and seconds
import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format
timeinhrs = timenow[11:19]
t=tm.time()#time.time() gives out time in seconds since epoch.
print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")
The output is
Time in HH:MM:SS format is: 13:32:45
Time since epoch is : 18793.335252338384 days
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
In my case I wanted to achieve format
"HH:MM:SS.fff".
I solved it like this:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:
mydate='2015-03-01'
df['datetime'] = datetime.datetime(mydate) + \
pandas.to_timedelta(df['seconds_since_midnight'], 's')
I looked every answers here and still tried my own
def a(t):
print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")
Results:
>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S
Python: 3.8.8
division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes
PS My code is unprofessional

timedelta64 presented with 0 days when smaller then 1 day [duplicate]

I get a start_date like this:
from django.utils.timezone import utc
import datetime
start_date = datetime.datetime.utcnow().replace(tzinfo=utc)
end_date = datetime.datetime.utcnow().replace(tzinfo=utc)
duration = end_date - start_date
I get output like this:
datetime.timedelta(0, 5, 41038)
How do I convert this into normal time like the following?
10 minutes, 1 hour like this
There's no built-in formatter for timedelta objects, but it's pretty easy to do it yourself:
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
Or, equivalently, if you're in Python 2.7+ or 3.2+:
seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
Now you can print it however you want:
'{} minutes, {} hours'.format(minutes, hours)
For example:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)
This will print:
9 minutes, 50 hours
If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:
print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
hours, 's' if minutes != 1 else '')
Or you may want to write an english_plural function to do the 's' bits for you, instead of repeating yourself.
From your comments, it sounds like you actually want to keep the days separate. That's even easier:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return days, hours, minutes, seconds
If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:
def dhms_to_seconds(days, hours, minutes, seconds):
return (((days * 24) + hours) * 60 + minutes) * 60 + seconds
def seconds_to_dhms(seconds):
days = seconds // (3600 * 24)
hours = (seconds // 3600) % 24
minutes = (seconds // 60) % 60
seconds = seconds % 60
return days, hours, minutes, seconds
So, putting it together:
def store_timedelta_in_database(thingy, duration):
seconds = dhms_to_seconds(*convert_timedelta(duration))
db.execute('INSERT INTO foo (thingy, duration) VALUES (?, ?)',
thingy, seconds)
db.commit()
def print_timedelta_from_database(thingy):
cur = db.execute('SELECT duration FROM foo WHERE thingy = ?', thingy)
seconds = int(cur.fetchone()[0])
days, hours, minutes, seconds = seconds_to_dhms(seconds)
print '{} took {} minutes, {} hours, {} days'.format(thingy, minutes, hours, days)
A datetime.timedelta corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).
If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:
x = datetime.timedelta(1, 5, 41038) # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60
There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.
>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'
I don't think it's a good idea to caculate yourself.
If you just want a pretty output, just covert it into str with str() function or directly print() it.
And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:
import datetime
delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()
Just use strftime :)
Something like that:
my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
print(my_date.strftime("%Y, %d %B"))
After edited your question to format timedelta, you could use:
def timedelta_tuple(timedelta_object):
return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60
# Try this code
from datetime import timedelta
class TimeDelta(timedelta):
def __str__(self):
_times = super(TimeDelta, self).__str__().split(':')
if "," in _times[0]:
_hour = int(_times[0].split(',')[-1].strip())
if _hour:
_times[0] += " hours" if _hour > 1 else " hour"
else:
_times[0] = _times[0].split(',')[0]
else:
_hour = int(_times[0].strip())
if _hour:
_times[0] += " hours" if _hour > 1 else " hour"
else:
_times[0] = ""
_min = int(_times[1])
if _min:
_times[1] += " minutes" if _min > 1 else " minute"
else:
_times[1] = ""
_sec = int(_times[2])
if _sec:
_times[2] += " seconds" if _sec > 1 else " second"
else:
_times[2] = ""
return ", ".join([i for i in _times if i]).strip(" ,").title()
# Test
>>> str(TimeDelta(seconds=10))
'10 Seconds'
>>> str(TimeDelta(seconds=60))
'01 Minute'
>>> str(TimeDelta(seconds=90))
'01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3000))
'50 Minutes'
>>> str(TimeDelta(seconds=3600))
'1 Hour'
>>> str(TimeDelta(seconds=3690))
'1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3660))
'1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3630))
'1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20))
'20 Hours'
>>> str(TimeDelta(seconds=3600*20 + 3000))
'20 Hours, 50 Minutes'
>>> str(TimeDelta(seconds=3600*20 + 3630))
'21 Hours, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20 + 3660))
'21 Hours, 01 Minute'
>>> str(TimeDelta(seconds=3600*20 + 3690))
'21 Hours, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24))
'1 Day'
>>> str(TimeDelta(seconds=3600*24 + 10))
'1 Day, 10 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 60))
'1 Day, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 90))
'1 Day, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3000))
'1 Day, 50 Minutes'
>>> str(TimeDelta(seconds=3600*24 + 3600))
'1 Day, 1 Hour'
>>> str(TimeDelta(seconds=3600*24 + 3630))
'1 Day, 1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3660))
'1 Day, 1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 3690))
'1 Day, 1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24*2))
'2 Days'
>>> str(TimeDelta(seconds=3600*24*2 + 9999))
'2 Days, 2 Hours, 46 Minutes, 39 Seconds'
I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
An alternative for this (older) question is to create a relative time from a timedelta converted to seconds. This can be accomplished using the time.gmtime(...) method that accepts seconds since the epoch:
>>> time.strftime("%H:%M:%S",time.gmtime(36901)) # secs = 36901
'10:15:01'
And, that's it! (NOTE: Here's a link to format specifiers for time.strftime() so the difference can be truncated to any units, as needed. ...)
Notably, this technique is also a great way to tell if your current time zone is actually in daylight savings time or not. (It provides an offset of 0 or 1 hours meaning it can be interpreted basically as a boolean.)
import datetime
import pytz
import time
pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'
This can be rendered to a method is_standard_time(...) where 1 means true and 0 means false.
Do you want to print the date in that format? This is the Python documentation: http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM
For the timedelta:
>>> a = datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)
But please notice, you should make sure it has the related value. For the above cases, it doesn't have the hours and minute values, and you should calculate from the seconds.
datetime.timedelta(hours=1, minutes=10)
#python 2.7

How to rount a number to tenth inside an 'int' function?

Here is my convert_seconds function:
def convert_seconds(x):
hour = int(round(x / 3600))
minute = int(round(x / 60 - hour * 60))
second = int(round(x - (hour * 3600 + minute * 60), 1))
return str(hour) + ' hours, ' + str(minute) + ' minutes, ' + str(second) +' seconds'
When i run my function:
>>>print convert_seconds(7261.7)
2 hours, 1 minute, 1 seconds
it print out "1 second" instead of "1.7 second"
Why is that?
How can I fix that?
NOTE: Output I need is:
>>>print convert_seconds(7261.7)
2 hours, 1 minute, 1.7 seconds
Thanks.
Why is that?
Because you explicitly turn the result into an integer, removing anything beyond the decimal point:
second = int(round(x - (hour * 3600 + minute * 60), 1))
How can I fix that?
Don't turn the seconds result into an integer:
second = round(x - (hour * 3600 + minute * 60), 1)
You should not round the hour and minute calculations; you should be flooring the results instead; int() by itself does that for you. Drop the round() calls for those two values. The // floor division operator would give you the same result as calling int() on the division result, removing the need to round or floor explicitly.
You can use formatting operations to then only show the values as decimals:
>>> def convert_seconds(x):
... hour = x // 3600
... minute = x // 60 - hour * 60
... second = x - (hour * 3600 + minute * 60)
... return '{:.0f} hours, {:.0f} minutes, {:.1f} seconds'.format(hour, minute, second)
...
>>> convert_seconds(7261.7)
'2 hours, 1 minutes, 1.7 seconds'
To round a floating point value to 1 decimal but drop the .0 if that is what it was rounded to, you'll need to explicitly string off the .0:
>>> def convert_seconds(x):
... hour = x // 3600
... minute = x // 60 - hour * 60
... second = x - (hour * 3600 + minute * 60)
... second_formatted = format(second, '.1f').rstrip('0').rstrip('.')
... return '{:.0f} hours, {:.0f} minutes, {} seconds'.format(hour, minute, second_formatted)
...
>>> convert_seconds(7261.7)
'2 hours, 1 minutes, 1.7 seconds'
>>> convert_seconds(7261)
'2 hours, 1 minutes, 1 seconds'
The expression format(second, '.1f').rstrip('0').rstrip('.') formats the seconds value but removes any .0 by first stripping 0 followed by stripping the remaining ..
Instead of division and subtraction, you may want to use the divmod() function:
def convert_seconds(x):
minutes, seconds = divmod(x, 60)
hours, minutes = divmod(minutes, 60)
second_formatted = format(seconds, '.1f').rstrip('0').rstrip('.')
return '{:.0f} hours, {:.0f} minutes, {} seconds'.format(hours, minutes, second_formatted)
The divmod() function returns the result of the quotient and the remainder; divmod(x, 60) returns the number of minutes (number of times 60 fits in x), and the remainder seconds. Apply the same function again on the number of minutes, and you get hours and a minutes remainder.
I think you have other problems here too ;-) For example,
>>> print convert_seconds(3500.0)
1 hours, -2 minutes, 20 seconds
In general, you're often rounding when you should be truncating. This is easier to do working with integers, so the following separates the argument into integer and fractional parts, does most work with integers, and puts the fractional part back at the end (but only if needed - if it's not 0.0):
def convert_seconds(x):
from math import modf
frac, whole = modf(x)
hours, leftover = divmod(int(whole), 3600)
minutes, seconds = divmod(leftover, 60)
if frac:
seconds += frac # change to float to get fraction
return "{} hours, {} minutes, {} seconds".format(
hours, minutes, seconds)
for case in 3500.0, 7261.7, 7325:
print case, "->", convert_seconds(case)
That prints:
3500.0 -> 0 hours, 58 minutes, 20 seconds
7261.7 -> 2 hours, 1 minutes, 1.7 seconds
7325 -> 2 hours, 2 minutes, 5 seconds
When you turn a float type into an int type, it will discard all decimal values and gives you the barebones integer underneath it all.
Try this:
def convert_seconds(x):
hour = int(round(x / 3600))
minute = int(round(x / 60 - hour * 60))
second = float(round(x - (hour * 3600 + minute * 60), 1))
return str(hour) + ' hours, ' + str(minute) + ' minutes, ' + str(second) +' seconds'
print(convert_seconds(7261.7))
You added a comment underneath where you asked, "yes but what about "convert_seconds(7325)", then seconds will be 5.0 instead of 5 "
You can do something like that to fix this problem. After doing the assignment to second:
second = float(round(x - (hour * 3600 + minute * 60), 1))
Do this:
second == int(second) if second == int(second) else second
"i don't want it to be float (5.0) but i want it to be round to (1.666666 ~ 1.7, not 2). how can i do that?"
You already do that! Your second argument to round is 1 which automatically rounds it off to one decimal place. Try doing convert_seconds(7261.6666) and this code will work.

Formatting python timedelta result [duplicate]

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.
You can just convert the timedelta to a string with str(). Here's an example:
import datetime
start = datetime.datetime(2009,2,10,14,00)
end = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00
As you know, you can get the total_seconds from a timedelta object by accessing the .seconds attribute.
Python provides the builtin function divmod() which allows for:
s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40
or you can convert to hours and remainder by using a combination of modulo and subtraction:
# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40
>>> str(datetime.timedelta(hours=10.56))
10:33:36
>>> td = datetime.timedelta(hours=10.505) # any timedelta object
>>> ':'.join(str(td).split(':')[:2])
10:30
Passing the timedelta object to the str() function calls the same formatting code used if we simply type print td. Since you don't want the seconds, we can split the string by colons (3 parts) and put it back together with only the first 2 parts.
def td_format(td_object):
seconds = int(td_object.total_seconds())
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', 60),
('second', 1)
]
strings=[]
for period_name, period_seconds in periods:
if seconds > period_seconds:
period_value , seconds = divmod(seconds, period_seconds)
has_s = 's' if period_value > 1 else ''
strings.append("%s %s%s" % (period_value, period_name, has_s))
return ", ".join(strings)
I personally use the humanize library for this:
>>> import datetime
>>> humanize.naturalday(datetime.datetime.now())
'today'
>>> humanize.naturalday(datetime.datetime.now() - datetime.timedelta(days=1))
'yesterday'
>>> humanize.naturalday(datetime.date(2007, 6, 5))
'Jun 05'
>>> humanize.naturaldate(datetime.date(2007, 6, 5))
'Jun 05 2007'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=1))
'a second ago'
>>> humanize.naturaltime(datetime.datetime.now() - datetime.timedelta(seconds=3600))
'an hour ago'
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.
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?
hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)
This works regardless if the time delta has even days or years.
Here is a general purpose function for converting either a timedelta object or a regular number (in the form of seconds or minutes, etc.) to a nicely formatted string. I took mpounsett's fantastic answer on a duplicate question, made it a bit more flexible, improved readibility, and added documentation.
You will find that it is the most flexible answer here so far since it allows you to:
Customize the string format on the fly instead of it being hard-coded.
Leave out certain time intervals without a problem (see examples below).
Function:
from string import Formatter
from datetime import timedelta
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = int(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = int(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = int(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
Demo:
>>> td = timedelta(days=2, hours=3, minutes=5, seconds=8, microseconds=340)
>>> print strfdelta(td)
02d 03h 05m 08s
>>> print strfdelta(td, '{D}d {H}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{D:2}d {H:2}:{M:02}:{S:02}')
2d 3:05:08
>>> print strfdelta(td, '{H}h {S}s')
51h 308s
>>> print strfdelta(12304, inputtype='s')
00d 03h 25m 04s
>>> print strfdelta(620, '{H}:{M:02}', 'm')
10:20
>>> print strfdelta(49, '{D}d {H}h', 'h')
2d 1h
I know that this is an old answered question, but I use datetime.utcfromtimestamp() for this. It takes the number of seconds and returns a datetime that can be formatted like any other datetime.
duration = datetime.utcfromtimestamp(end - begin)
print duration.strftime('%H:%M')
As long as you stay in the legal ranges for the time parts this should work, i.e. it doesn't return 1234:35 as hours are <= 23.
maybe:
>>> import datetime
>>> dt0 = datetime.datetime(1,1,1)
>>> td = datetime.timedelta(minutes=34, hours=12, seconds=56)
>>> (dt0+td).strftime('%X')
'12:34:56'
>>> (dt0+td).strftime('%M:%S')
'34:56'
>>> (dt0+td).strftime('%H:%M')
'12:34'
>>>
I would seriously consider the Occam's Razor approach here:
td = str(timedelta).split('.')[0]
This returns a string without the microseconds
If you want to regenerate the datetime.timedelta object, just do this:
h,m,s = re.split(':', td)
new_delta = datetime.timedelta(hours=int(h),minutes=int(m),seconds=int(s))
2 years in, I love this language!
I used the humanfriendly python library to do this, it works very well.
import humanfriendly
from datetime import timedelta
delta = timedelta(seconds = 321)
humanfriendly.format_timespan(delta)
'5 minutes and 21 seconds'
Available at https://pypi.org/project/humanfriendly/
Questioner wants a nicer format than the typical:
>>> import datetime
>>> datetime.timedelta(seconds=41000)
datetime.timedelta(0, 41000)
>>> str(datetime.timedelta(seconds=41000))
'11:23:20'
>>> str(datetime.timedelta(seconds=4102.33))
'1:08:22.330000'
>>> str(datetime.timedelta(seconds=413302.33))
'4 days, 18:48:22.330000'
So, really there's two formats, one where days are 0 and it's left out, and another where there's text "n days, h:m:s". But, the seconds may have fractions, and there's no leading zeroes in the printouts, so columns are messy.
Here's my routine, if you like it:
def printNiceTimeDelta(stime, etime):
delay = datetime.timedelta(seconds=(etime - stime))
if (delay.days > 0):
out = str(delay).replace(" days, ", ":")
else:
out = "0:" + str(delay)
outAr = out.split(':')
outAr = ["%02d" % (int(float(x))) for x in outAr]
out = ":".join(outAr)
return out
this returns output as dd:hh:mm:ss format:
00:00:00:15
00:00:00:19
02:01:31:40
02:01:32:22
I did think about adding years to this, but this is left as an exercise for the reader, since the output is safe at over 1 year:
>>> str(datetime.timedelta(seconds=99999999))
'1157 days, 9:46:39'
My datetime.timedelta objects went greater than a day. So here is a further problem. All the discussion above assumes less than a day. A timedelta is actually a tuple of days, seconds and microseconds. The above discussion should use td.seconds as joe did, but if you have days it is NOT included in the seconds value.
I am getting a span of time between 2 datetimes and printing days and hours.
span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)
I have a function:
def period(delta, pattern):
d = {'d': delta.days}
d['h'], rem = divmod(delta.seconds, 3600)
d['m'], d['s'] = divmod(rem, 60)
return pattern.format(**d)
Examples:
>>> td = timedelta(seconds=123456789)
>>> period(td, "{d} days {h}:{m}:{s}")
'1428 days 21:33:9'
>>> period(td, "{h} hours, {m} minutes and {s} seconds, {d} days")
'21 hours, 33 minutes and 9 seconds, 1428 days'
Following Joe's example value above, I'd use the modulus arithmetic operator, thusly:
td = datetime.timedelta(hours=10.56)
td_str = "%d:%d" % (td.seconds/3600, td.seconds%3600/60)
Note that integer division in Python rounds down by default; if you want to be more explicit, use math.floor() or math.ceil() as appropriate.
One liner. Since timedeltas do not offer datetime's strftime, bring the timedelta back to a datetime, and use stftime.
This can not only achieve the OP's requested format Hours:Minutes, now you can leverage the full formatting power of datetime's strftime, should your requirements change to another representation.
import datetime
td = datetime.timedelta(hours=2, minutes=10, seconds=5)
print(td)
print(datetime.datetime.strftime(datetime.datetime.strptime(str(td), "%H:%M:%S"), "%H:%M"))
Output:
2:10:05
02:10
This also solves the annoyance that timedeltas are formatted into strings as H:MM:SS rather than HH:MM:SS, which lead me to this problem, and the solution I've shared.
import datetime
hours = datetime.timedelta(hours=16, minutes=30)
print((datetime.datetime(1,1,1) + hours).strftime('%H:%M'))
def seconds_to_time_left_string(total_seconds):
s = int(total_seconds)
years = s // 31104000
if years > 1:
return '%d years' % years
s = s - (years * 31104000)
months = s // 2592000
if years == 1:
r = 'one year'
if months > 0:
r += ' and %d months' % months
return r
if months > 1:
return '%d months' % months
s = s - (months * 2592000)
days = s // 86400
if months == 1:
r = 'one month'
if days > 0:
r += ' and %d days' % days
return r
if days > 1:
return '%d days' % days
s = s - (days * 86400)
hours = s // 3600
if days == 1:
r = 'one day'
if hours > 0:
r += ' and %d hours' % hours
return r
s = s - (hours * 3600)
minutes = s // 60
seconds = s - (minutes * 60)
if hours >= 6:
return '%d hours' % hours
if hours >= 1:
r = '%d hours' % hours
if hours == 1:
r = 'one hour'
if minutes > 0:
r += ' and %d minutes' % minutes
return r
if minutes == 1:
r = 'one minute'
if seconds > 0:
r += ' and %d seconds' % seconds
return r
if minutes == 0:
return '%d seconds' % seconds
if seconds == 0:
return '%d minutes' % minutes
return '%d minutes and %d seconds' % (minutes, seconds)
for i in range(10):
print pow(8, i), seconds_to_time_left_string(pow(8, i))
Output:
1 1 seconds
8 8 seconds
64 one minute and 4 seconds
512 8 minutes and 32 seconds
4096 one hour and 8 minutes
32768 9 hours
262144 3 days
2097152 24 days
16777216 6 months
134217728 4 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:
def td2HHMMstr(td):
'''Convert timedelta objects to a HH:MM string with (+/-) sign'''
if td < datetime.timedelta(seconds=0):
sign='-'
td = -td
else:
sign = ''
tdhours, rem = divmod(td.total_seconds(), 3600)
tdminutes, rem = divmod(rem, 60)
tdstr = '{}{:}:{:02d}'.format(sign, int(tdhours), int(tdminutes))
return tdstr
timedelta to HH:MM string:
td2HHMMstr(datetime.timedelta(hours=1, minutes=45))
'1:54'
td2HHMMstr(datetime.timedelta(days=2, hours=3, minutes=2))
'51:02'
td2HHMMstr(datetime.timedelta(hours=-3, minutes=-2))
'-3:02'
td2HHMMstr(datetime.timedelta(days=-35, hours=-3, minutes=-2))
'-843:02'
from django.utils.translation import ngettext
def localize_timedelta(delta):
ret = []
num_years = int(delta.days / 365)
if num_years > 0:
delta -= timedelta(days=num_years * 365)
ret.append(ngettext('%d year', '%d years', num_years) % num_years)
if delta.days > 0:
ret.append(ngettext('%d day', '%d days', delta.days) % delta.days)
num_hours = int(delta.seconds / 3600)
if num_hours > 0:
delta -= timedelta(hours=num_hours)
ret.append(ngettext('%d hour', '%d hours', num_hours) % num_hours)
num_minutes = int(delta.seconds / 60)
if num_minutes > 0:
ret.append(ngettext('%d minute', '%d minutes', num_minutes) % num_minutes)
return ' '.join(ret)
This will produce:
>>> from datetime import timedelta
>>> localize_timedelta(timedelta(days=3660, minutes=500))
'10 years 10 days 8 hours 20 minutes'
A straight forward template filter for this problem. The built-in function int() never rounds up. F-Strings (i.e. f'') require python 3.6.
#app_template_filter()
def diffTime(end, start):
diff = (end - start).total_seconds()
d = int(diff / 86400)
h = int((diff - (d * 86400)) / 3600)
m = int((diff - (d * 86400 + h * 3600)) / 60)
s = int((diff - (d * 86400 + h * 3600 + m *60)))
if d > 0:
fdiff = f'{d}d {h}h {m}m {s}s'
elif h > 0:
fdiff = f'{h}h {m}m {s}s'
elif m > 0:
fdiff = f'{m}m {s}s'
else:
fdiff = f'{s}s'
return fdiff
If you happen to have IPython in your packages (you should), it has (up to now, anyway) a very nice formatter for durations (in float seconds). That is used in various places, for example by the %%time cell magic. I like the format it produces for short durations:
>>> from IPython.core.magics.execution import _format_time
>>>
>>> for v in range(-9, 10, 2):
... dt = 1.25 * 10**v
... print(_format_time(dt))
1.25 ns
125 ns
12.5 µs
1.25 ms
125 ms
12.5 s
20min 50s
1d 10h 43min 20s
144d 16h 13min 20s
14467d 14h 13min 20s
I continued from MarredCheese's answer and added year, month, millicesond and microsecond
all numbers are formatted to integer except for second, thus the fraction of a second can be customized.
#kfmfe04 asked for fraction of a second so I posted this solution
In the main there are some examples.
from string import Formatter
from datetime import timedelta
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02.0f}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02.0f}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02.0f}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02.0f}' --> ' 5d 8:04:02'
'{H}h {S:.0f}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = tdelta.total_seconds()
elif inputtype in ['s', 'seconds']:
remainder = float(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = float(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = float(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = float(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = float(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('Y','m','W', 'D', 'H', 'M', 'S', 'mS', 'µS')
constants = {'Y':86400*365.24,'m': 86400*30.44 ,'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1, 'mS': 1/pow(10,3) , 'µS':1/pow(10,6)}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
Quotient, remainder = divmod(remainder, constants[field])
values[field] = int(Quotient) if field != 'S' else Quotient + remainder
return f.format(fmt, **values)
if __name__ == "__main__":
td = timedelta(days=717, hours=3, minutes=5, seconds=8, microseconds=3549)
print(strfdelta(td,'{Y} years {m} months {W} weeks {D} days {H:02}:{M:02}:{S:02}'))
print(strfdelta(td,'{m} months {W} weeks {D} days {H:02}:{M:02}:{S:02.4f}'))
td = timedelta( seconds=8, microseconds=8549)
print(strfdelta(td,'{S} seconds {mS} milliseconds {µS} microseconds'))
print(strfdelta(td,'{S:.0f} seconds {mS} milliseconds {µS} microseconds'))
print(strfdelta(pow(10,7),inputtype='s'))
Output:
1 years 11 months 2 weeks 3 days 01:09:56.00354900211096
23 months 2 weeks 3 days 00:12:20.0035
8.008549 seconds 8 milliseconds 549 microseconds
8 seconds 8 milliseconds 549 microseconds
115d 17h 46m 40s
Here's a function to stringify timedelta.total_seconds(). It works in python 2 and 3.
def strf_interval(seconds):
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
return '{} {} {} {}'.format(
"" if int(days) == 0 else str(int(days)) + ' days',
"" if int(hours) == 0 else str(int(hours)) + ' hours',
"" if int(minutes) == 0 else str(int(minutes)) + ' mins',
"" if int(seconds) == 0 else str(int(seconds)) + ' secs'
)
Example output:
>>> print(strf_interval(1))
1 secs
>>> print(strf_interval(100))
1 mins 40 secs
>>> print(strf_interval(1000))
16 mins 40 secs
>>> print(strf_interval(10000))
2 hours 46 mins 40 secs
>>> print(strf_interval(100000))
1 days 3 hours 46 mins 40 secs
timedelta to string, use for print running time info.
def strfdelta_round(tdelta, round_period='second'):
"""timedelta to string, use for measure running time
attend period from days downto smaller period, round to minimum period
omit zero value period
"""
period_names = ('day', 'hour', 'minute', 'second', 'millisecond')
if round_period not in period_names:
raise Exception(f'round_period "{round_period}" invalid, should be one of {",".join(period_names)}')
period_seconds = (86400, 3600, 60, 1, 1/pow(10,3))
period_desc = ('days', 'hours', 'mins', 'secs', 'msecs')
round_i = period_names.index(round_period)
s = ''
remainder = tdelta.total_seconds()
for i in range(len(period_names)):
q, remainder = divmod(remainder, period_seconds[i])
if int(q)>0:
if not len(s)==0:
s += ' '
s += f'{q:.0f} {period_desc[i]}'
if i==round_i:
break
if i==round_i+1:
s += f'{remainder} {period_desc[round_i]}'
break
return s
e.g. auto omit zero leading period:
>>> td = timedelta(days=0, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'second')
'2 hours 5 mins 8 secs'
or omit middle zero period:
>>> td = timedelta(days=2, hours=0, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'millisecond')
'2 days 5 mins 8 secs 3 msecs'
or round to minutes, omit below minutes:
>>> td = timedelta(days=1, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'minute')
'1 days 2 hours 5 mins'
Please check this function - it converts timedelta object into string 'HH:MM:SS'
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
If you already have a timedelta obj then just convert that obj into string. Remove the last 3 characters of the string and print. This will truncate the seconds part and print the rest of it in the format Hours:Minutes.
t = str(timedeltaobj)
print t[:-3]
I wanted to do this so wrote a simple function. It works great for me and is quite versatile (supports years to microseconds, and any granularity level, e.g. you can pick between '2 days, 4 hours, 48 minutes' and '2 days, 4 hours' and '2 days, 4.8 hours', etc.
def pretty_print_timedelta(t, max_components=None, max_decimal_places=2):
'''
Print a pretty string for a timedelta.
For example datetime.timedelta(days=2, seconds=17280) will be printed as '2 days, 4 hours, 48 minutes'. Setting max_components to e.g. 1 will change this to '2.2 days', where the
number of decimal points can also be set.
'''
time_scales = [timedelta(days=365), timedelta(days=1), timedelta(hours=1), timedelta(minutes=1), timedelta(seconds=1), timedelta(microseconds=1000), timedelta(microseconds=1)]
time_scale_names_dict = {timedelta(days=365): 'year',
timedelta(days=1): 'day',
timedelta(hours=1): 'hour',
timedelta(minutes=1): 'minute',
timedelta(seconds=1): 'second',
timedelta(microseconds=1000): 'millisecond',
timedelta(microseconds=1): 'microsecond'}
count = 0
txt = ''
first = True
for scale in time_scales:
if t >= scale:
count += 1
if count == max_components:
n = t / scale
else:
n = int(t / scale)
t -= n*scale
n_txt = str(round(n, max_decimal_places))
if n_txt[-2:]=='.0': n_txt = n_txt[:-2]
txt += '{}{} {}{}'.format('' if first else ', ', n_txt, time_scale_names_dict[scale], 's' if n>1 else '', )
if first:
first = False
if len(txt) == 0:
txt = 'none'
return txt
I had the same problem and I am using pandas Timedeltas, didn't want to bring in additional dependencies (another answer mentions humanfriendly) so I wrote this small function to print out only the relevant information:
def format_timedelta(td: pd.Timedelta) -> str:
if pd.isnull(td):
return str(td)
else:
c = td.components._asdict()
return ", ".join(f"{n} {unit}" for unit, n in c.items() if n)
For example, pd.Timedelta(hours=3, seconds=12) would print as 3 hours, 12 seconds.
I suggest the following method so that we can utilize the standard formatting function, pandas.Timestamp.strftime!
from pandas import Timestamp, Timedelta
(Timedelta("2 hours 30 min") + Timestamp("00:00:00")).strftime("%H:%M")

How do I convert seconds to hours, minutes and seconds?

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.
Is there an easy way to convert the seconds to this format in Python?
You can use datetime.timedelta function:
>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'
By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
And then use string formatting to convert the result into your desired output:
print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
I can hardly name that an easy way (at least I can't remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:
from time import strftime
from time import gmtime
strftime("%H:%M:%S", gmtime(666))
'00:11:06'
strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'
gmtime is used to convert seconds to special tuple format that strftime() requires.
Note: Truncates after 23:59:59
Using datetime:
With the ':0>8' format:
from datetime import timedelta
"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Without the ':0>8' format:
"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'
"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'
"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'
Using time:
from time import gmtime
from time import strftime
# NOTE: The following resets if it goes over 23:59:59!
strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'
strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'
strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'
strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit:
https://humanfriendly.readthedocs.io/en/latest/api.html#humanfriendly.format_timespan
The following set worked for me.
def sec_to_hours(seconds):
a=str(seconds//3600)
b=str((seconds%3600)//60)
c=str((seconds%3600)%60)
d=["{} hours {} mins {} seconds".format(a, b, c)]
return d
print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']
print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']
A bit off topic answer but maybe useful to someone
def time_format(seconds: int) -> str:
if seconds is not None:
seconds = int(seconds)
d = seconds // (3600 * 24)
h = seconds // 3600 % 24
m = seconds % 3600 // 60
s = seconds % 3600 % 60
if d > 0:
return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
elif h > 0:
return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
elif m > 0:
return '{:02d}m {:02d}s'.format(m, s)
elif s > 0:
return '{:02d}s'.format(s)
return '-'
Results in:
print(time_format(25*60*60 + 125))
>>> 01D 01H 02m 05s
print(time_format(17*60*60 + 35))
>>> 17H 00m 35s
print(time_format(3500))
>>> 58m 20s
print(time_format(21))
>>> 21s
This is how I got it.
def sec2time(sec, n_msec=3):
''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
if hasattr(sec,'__len__'):
return [sec2time(s) for s in sec]
m, s = divmod(sec, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
if n_msec > 0:
pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
else:
pattern = r'%02d:%02d:%02d'
if d == 0:
return pattern % (h, m, s)
return ('%d days, ' + pattern) % (d, h, m, s)
Some examples:
$ sec2time(10, 3)
Out: '00:00:10.000'
$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'
$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'
$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']
hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)
minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)
similarly, seconds (s) by remainder of hour and minutes calculation.
Rest is just string formatting!
def hms(seconds):
h = seconds // 3600
m = seconds % 3600 // 60
s = seconds % 3600 % 60
return '{:02d}:{:02d}:{:02d}'.format(h, m, s)
print(hms(7500)) # Should print 02h05m00s
If you need to get datetime.time value, you can use this trick:
my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
You cannot add timedelta to time, but can add it to datetime.
UPD: Yet another variation of the same technique:
my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.
dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.
from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
int(rt.hours), int(rt.minutes), int(rt.seconds)))
Prints
40.0
01:30:40
Here is a way that I always use: (no matter how inefficient it is)
seconds = 19346
def zeroes (num):
if num < 10: num = "0" + num
return num
def return_hms(second, apply_zeroes):
sec = second % 60
min_ = second // 60 % 60
hrs = second // 3600
if apply_zeroes > 0:
sec = zeroes(sec)
min_ = zeroes(min_)
if apply_zeroes > 1:
hrs = zeroes(hrs)
return "{}:{}:{}".format(hrs, min_, sec)
print(return_hms(seconds, 1))
RESULT:
5:22:26
Syntax of return_hms() function
The return_hms() function is used like this:
The first variable (second) is the amount of seconds you want to convert into h:m:s.
The second variable (apply_zeroes) is formatting:
0 or less: Apply no zeroes whatsoever
1: Apply zeroes to minutes and seconds when they're below 10.
2 or more: Apply zeroes to any value (including hours) when they're below 10.
Here is a simple program that reads the current time and converts it to a time of day in hours, minutes, and seconds
import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format
timeinhrs = timenow[11:19]
t=tm.time()#time.time() gives out time in seconds since epoch.
print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")
The output is
Time in HH:MM:SS format is: 13:32:45
Time since epoch is : 18793.335252338384 days
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
In my case I wanted to achieve format
"HH:MM:SS.fff".
I solved it like this:
timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'
The solutions above will work if you're looking to convert a single value for "seconds since midnight" on a date to a datetime object or a string with HH:MM:SS, but I landed on this page because I wanted to do this on a whole dataframe column in pandas. If anyone else is wondering how to do this for more than a single value at a time, what ended up working for me was:
mydate='2015-03-01'
df['datetime'] = datetime.datetime(mydate) + \
pandas.to_timedelta(df['seconds_since_midnight'], 's')
I looked every answers here and still tried my own
def a(t):
print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")
Results:
>>> a(7500)
2H 5M 0S
>>> a(3666)
1H 1M 6S
Python: 3.8.8
division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes
PS My code is unprofessional

Categories