-1

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

sophros
  • 11,665
  • 7
  • 38
  • 61
Ido Barash
  • 4,548
  • 9
  • 38
  • 72
  • Does this answer your question? [How can I produce a human readable difference when subtracting two UNIX timestamps using Python?](https://stackoverflow.com/questions/6574329/how-can-i-produce-a-human-readable-difference-when-subtracting-two-unix-timestam) – sophros May 18 '21 at 11:04

2 Answers2

1

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

S.B
  • 7,457
  • 5
  • 15
  • 37
1

You may want to have a look at humanize python library:

>>> humanize.naturaldelta(dt.timedelta(seconds=1001))
'16 minutes'
sophros
  • 11,665
  • 7
  • 38
  • 61