Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format timedelta to string

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.

like image 642
mawcs Avatar asked Feb 11 '09 20:02

mawcs


People also ask

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.

How do you convert Timedelta to INT?

Convert the timedelta to int Using the dt Attribute in Pandas. To convert the timedelta to an integer value, we can use the pandas library's dt attribute. The dt attribute allows us to extract components of the timedelta . For example, we can extract the year, month, day, minutes, or seconds using the dt attribute.

How do I convert a date to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


1 Answers

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 
like image 157
Parand Avatar answered Oct 19 '22 07:10

Parand