`datetime.strftime` and `datetime.strptime` interprete %Y differently
Solution 1
I like your idea of using a try..except
to validate the input, since in some future version of Python, years < 1000 might be acceptable.
This comment in the code suggests this restriction is limited to Python's current implementation of strftime.
In Python 2.7, the exception occurs for years < 1900
, but
in Python 3.2, the exception occurs for years < 1000
:
import datetime as dt
format = "%Y-%m-%d"
t = dt.datetime.strptime("0023-10-10", format)
try:
t.strftime(format)
except ValueError as err:
print(err)
prints
year=23 is before 1000; the datetime strftime() methods require year >= 1000
Solution 2
You could simply check if t.year < 1900
and if it is return an error. No need to deliberately cause an exception.
Comments
-
satoru almost 2 years
I use a statement as shown below to create a
datetime
object from a string:t = datetime.strptime("0023-10-10", "%Y-%m-%d")
Later, somewhere in my code uses the
t
object and invoke thestrftime
method with the same format string:t.strftime("%Y-%m-%d")
This causes a
ValueError: year=23 is before 1900; the datetime strftime() methods require year >= 1900
.It seems that the validation of the %Y input is different in this two similar methods. So I have to do the following to make sure I don't accept some bad years like
23
:try: format = "%Y-%m-%d" t = datetime.strptime("0023-10-10", format) t.strftime(format) except ValueError: ...
I wonder if there's a better way to do this validation.
-
satoru over 12 yearsThx for replying. By the way, do you have any idea why these to method behave differently?
-
satoru over 12 yearsI still don't understand why this restriction is not applied to
strptime
. -
unutbu over 12 years
datetime.strftime
ultimately calls some C function,strftime.
The implementation used is restricted to years >= 1900, or 1000 depending on the version of Python. strptime is implemented in Python, and does not have the same restriction. See this feature request.