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

点点圈 提交于 2019-12-05 06:52:10

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

You could simply check if t.year < 1900 and if it is return an error. No need to deliberately cause an exception.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!