Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format timedelta greater than 24 hours for display only containing hours?

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?

like image 991
SparkAndShine Avatar asked Dec 07 '15 13:12

SparkAndShine


People also ask

How do I get Timedelta with only time?

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 do I convert Timedelta to hours in Python?

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.

How do I change Timedelta format in Python?

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.

What is the use of Timedelta () function?

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.


2 Answers

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'
like image 168
Yuri G. Avatar answered Sep 19 '22 17:09

Yuri G.


td = datetime.timedelta(hours=36, minutes=10, seconds=10)
seconds = td.total_seconds()
result = '%d:%02d:%02d' % (seconds / 3600, seconds / 60 % 60, seconds % 60)
like image 39
user7894079 Avatar answered Sep 22 '22 17:09

user7894079