pythonpython-datetimevalueerrorstrptimestrftime

How can I print a day and a time using Python strftime?


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.


Solution

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

    You can use this format instead.