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 cl
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!
timedelta to string, use for print running time info.
def strf_runningtime(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'
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.
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
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
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)