0

Context: I'm trying to format a day and time using Python's strftime function, but I'm encountering a "ValueError." I want the output to be in the format "1 day, 2:45:00" to represent a valid datetime object. However, my current code is throwing the following error: "ValueError: time data '1 day, 2:45:00' does not match format '%H:%M:%S'." .

from datetime import datetime


actualTime = '1 day, 2:45:00'
strpTime = datetime.strptime(f"{actualTime}", "%H:%M:%S")
fomtTime = strpTime.strftime("%I:%M %p")
print(fomtTime)

Issue: I would like to know how to format a day and time in the desired format ("1 day, 2:45:00") using Python's strftime function without encountering a ValueError. I appreciate any insights or corrections to my code.

Thank you.

  • 1
    The immediate problem is that you're asking Python to parse your string with a format of `hour:minutes:seconds`, but your sting also includes `"1 day, "`. Perhaps more importantly, what kind of date is "1 day"? How do you *want* that interpreted? – CrazyChucky Dec 27 '22 at 23:24
  • I want the output to be **1 day, 2:45:00**, so that it can be a valid datetime object. – Baboucarr Badjie Dec 27 '22 at 23:31
  • Because I want to format it with strftime. And I believe that cannot be done if it is not a valid datetime object. – Baboucarr Badjie Dec 27 '22 at 23:33
  • It looks more a `timedelta` than a `datetime` – norok2 Dec 27 '22 at 23:35
  • @norok2, sure, but `timedelta` has not `strptime`, and you can make `datetime.strptime` work, [usually](https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string) – Him Dec 27 '22 at 23:37
  • @Him so how do I make it work? – Baboucarr Badjie Dec 27 '22 at 23:43

1 Answers1

1
'%d day, %H:%M:%S'

You can use this format instead.

inthewest
  • 26
  • 2
  • actualTime = '1 day, 2:45:00' strpTime = datetime.strptime(f"{actualTime}", '%d day, %H:%M:%S') fomtTime = strpTime.strftime("%I:%M %p") print(fomtTime) – inthewest Dec 27 '22 at 23:49