Consider the following example:
from datetime import datetime
FMT = "%Y-%m-%dT%H:%M:%S"
original_date = datetime(1,1,1)
s = original_date.strftime(FMT) # This is '1-01-01T00:00:00'
When I now try to parse that string back into a datetime with the exact format I used to serialize it in the first place, a ValueError
is thrown at me:
datetime.strptime(s, FMT)
ValueError: time data '1-01-01T00:00:00' does not match format '%Y-%m-%dT%H:%M:%S'
However
datetime.strptime('0001-01-01T00:00:00', FMT)
works as expected.
I would have expected strptime
to be able to handle whatever strftime
produces. I always regarded those functions to be the inverse of each other.
Why does original_date.strftime(FMT)
not result in a zero-padded year? Is there any reason for this inconsistency?
The results for %Y
are not consistent across platforms. On Mac OS X it'll return 0001
but on Linux it returns 1
.
On Linux you can use %4Y
to produce 0001
as year value.
This is a known issue: https://bugs.python.org/issue13305.
The documentation for strftime()
and strptime()
also states:
The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With