How do I format timedelta greater than 24 hours for display only containing hours in Python?
>>> import datetime
>>> td = datetime.timedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
'1 day, 12:10:10'
# my expected result is:
'36:10:10'
I acheive it by:
import datetime
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
>>> print(str)
36:10:10
Is there a better way?
I assume you want to extract the time component as a string, removing all reference to "days" even if your Timedelta is greater than 1 day. One way is to convert your Timedelta to a normalised datetime and then use the time attribute. Below is also a trivial way to convert your Timedelta objects to strings.
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.
Convert String to TimeDelta We can even convert time in string format to datetime by using the strptime() function and then extracting the timedelta information using the timedelta module. We can use the repr(td) to print the timedelta as a constructor with attributes in a string format.
timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
May be defining your class that inherits datetime.timedelta
will be a little more elegant
class mytimedelta(datetime.timedelta):
def __str__(self):
seconds = self.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
str = '{}:{}:{}'.format(int(hours), int(minutes), int(seconds))
return (str)
td = mytimedelta(hours=36, minutes=10, seconds=10)
>>> str(td)
prints '36:10:10'
td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With