0

How can you convert the timedelta so that it only outputs "09:50" as a string instead of output: "9:50:00"?

from datetime import timedelta

y = 3
x = 30

time1 = timedelta(hours=6, minutes=20)
time2 = timedelta(hours=y, minutes=x)

future = time1 + time2

print(future)

future_str = str(future)

print(future_str)
Michael Ruth
  • 2,938
  • 1
  • 20
  • 27
red
  • 1
  • 2
  • Possible duplicates: https://stackoverflow.com/questions/538666/format-timedelta-to-string https://stackoverflow.com/questions/8906926/formatting-timedelta-objects – LeoD Dec 05 '22 at 09:42

4 Answers4

1

Code that works is:

from datetime import datetime, timedelta
y = 3
x = 30
time1 = timedelta(hours=6, minutes=20)
time2 = timedelta(hours=y, minutes=x)
future = time1 + time2
s = (datetime(1, 1, 1) + future).strftime("%H:%M")
print(s)
>>> 09:50

Explanation: timedelta doesn't have strftime() method, that's why other answers are failing, so we need to convert it back to datetime, an easy trick is to add a dummy datetime object

svfat
  • 3,273
  • 1
  • 15
  • 34
  • Hi Svfat, thank you its works! one more please i am a beginner could you explain to me what you did ? What makes date time(1,1,1) ? – red Dec 05 '22 at 10:02
  • datetime(1,1,1) is just a "dummy" datetime object, this of this like of a beginning of the timeline (year zero) when we adding timedelta object to it, we are getting another datetime object, which has strftime method to convert it to the proper format so it is like 00:00 + 09:50 – svfat Dec 05 '22 at 10:10
0

If you already have string "9:50:00" you can just slice it.

future_str = "9:50:00"[0:4]

Jora Karyan
  • 66
  • 1
  • 9
0

Try:

'{:0>8}'.format(future_str)[:5])
-1

use strftime("%H:%M") which helps to format your time example code below

future_str = future.strftime("%H:%M")

It return => 09:50

chrslg
  • 9,023
  • 5
  • 17
  • 31