HACKER Q&A
📣 hamid_rostami

Python Datetime Conversion


I was working with Python datetime module and came across this corner case. The following assertion will fail:

SRC = "09/23/2024 12:00:00 AM"

FMT = "%m/%d/%Y %H:%M:%S %p"

assert datetime.datetime.strptime(SRC, FMT).strftime(FMT) == SRC

Basically I'm converting SRC to datetime object and then back to its original string form. It fails because the resulting string is: "09/23/2024 12:00:00 PM"

I was working with a web API and storing datetime objects upon receiving them within the response body. When it comes to hand them in again in the following requests, the backend was giving error, since it was expecting AM not PM!

I was wondering if this behavior was expected or this shouldn't be the right way to handle midnight?

Anyway it's funny and could cause spectacular failure in our software :)


  👤 saintamh Accepted Answer ✓
I think it’s because you’re using %H whereas what you want is %I