1

Pretty basic question. I'm using a function that parses seconds from JSON and uses datetime in Python to output to hours/minutes/seconds, like so:

str(datetime.timedelta(seconds=seconds here))

This outputs something like so:

Timestamp: 23:54:02.513000
Timestamp: 1 day, 0:01:07.827000

It works perfectly, but I don't want datetime to print "1 day", I want hours only. So for example the second above should be something like 24:01:07.827000

I tried using my own custom function to convert the seconds, but I feel there must be an easier way.

1 Answers1

1

According to Python Docs, https://docs.python.org/3/library/datetime.html#timedelta-objects

Only days, seconds and microseconds are stored internally.

So you have to compute the hours and minutes yourself using days and seconds. Below code uses f-strings.

import datetime

t = datetime.timedelta(seconds=60*60*24 + 11569) # A random number for testing

print(t) # 1 day, 3:12:49
print(f'{t.days * 24 + t.seconds // 3600:02}:{(t.seconds % 3600) // 60:02}:{t.seconds % 60:02}') # 27:12:49
Aditya
  • 315
  • 1
  • 9