`datetime.strftime` and` datetime.strptime` interpret% Y differently

I use the instruction 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, the t object is used and the strftime method is called with the same format string:

t.strftime("%Y-%m-%d")

This results in a ValueError: year=23 is before 1900; the datetime strftime() methods require year >= 1900 ValueError: year=23 is before 1900; the datetime strftime() methods require year >= 1900 .

It seems that the validation of input% Y differs in two similar methods. Therefore, I must do the following to make sure that I do not accept some bad years, for example 23 :

 try: format = "%Y-%m-%d" t = datetime.strptime("0023-10-10", format) t.strftime(format) except ValueError: ... 

I wonder if there is a better way to do this check.

+6
source share
2 answers

I like your idea of ​​using try..except to validate input, since in some future version of Python, years <1000 may be acceptable.

This commentary in the code suggests that this limitation is limited to the current Python implementation of strftime.


In Python 2.7, an exception occurs for years < 1900 , but in Python 3.2 an 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 
+4
source

You can simply check if t.year < 1900 and return an error. There is no need to deliberately throw an exception.

+2
source

Source: https://habr.com/ru/post/902541/


All Articles