News for hackers. Stuff that matters.

Ask HN: 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 :)

( 2 comments | on HN )
Re:Ask HN: Python Datetime Conversion by saintamh on Sunday September 29, 2024 @12:44PM (#41688560)
I think it’s because you’re using %H whereas what you want is %I
Re:Ask HN: Python Datetime Conversion by hamid_rostami on Sunday September 29, 2024 @12:52PM (#41688594)
Well spotted, that fixes the issue, thanks!