Search code examples
pythonpython-3.xtimedelta

python convert timedelta to meaningful string such as "1 hours"


I want to convert a python timedelta object to an easy to read meaningful string

for example:

0 1:0:0 -> 1 hours
0 0:5:0. -> 5 minutes
2 0:0:0. ->. 2 days

any ideas how to do that?

Thanks


Solution

  • Actually timedelta class, provides you days, seconds, microseconds property directly. But in order to get "hours" and "minutes" you can do some simple calculations yourself.

    import datetime
    
    d1 = datetime.datetime(2012, 4, 20, second=10, microsecond=14)
    d2 = datetime.datetime(2012, 3, 20, second=8, microsecond=4)
    delta = d1 - d2
    
    print(delta)
    print(delta.days)
    print(delta.seconds)
    print(delta.microseconds)
    

    Divide seconds by 60 to get minutes, by 3600 to get hours