Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 the strftime 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.

like image 376
satoru Avatar asked Nov 28 '11 11:11

satoru


People also ask

What is difference between Strftime and Strptime?

strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.

What is datetime datetime Strptime?

Python DateTime – strptime() Function strptime() is another method available in DateTime which is used to format the time stamp which is in string format to date-time object.

What does datetime Strftime do?

The strftime() function is used to convert date and time objects to their string representation. It takes one or more input of formatted code and returns the string representation. Returns : It returns the string representation of the date or time object.


1 Answers

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
like image 133
unutbu Avatar answered Oct 07 '22 06:10

unutbu