`datetime.strftime`和`datetime.strptime` interprete%Y不同 [英] `datetime.strftime` and `datetime.strptime` interprete %Y differently

查看:166
本文介绍了`datetime.strftime`和`datetime.strptime` interprete%Y不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用如下所示的语句从字符串中创建一个 datetime 对象:

I use a statement as shown below to create a datetime object from a string:

t = datetime.strptime(0023-10-10,%Y-%m-%d)

后来,我的代码中的某个地方使用 t 对象,并使用相同的格式字符串调用 strftime 方法:

Later, somewhere in my code uses the t object and invoke the strftime method with the same format string:

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

这导致$ code> ValueError:year = 23是在1900之前; datetime strftime()方法需要年> = 1900 。

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

似乎这个%Y输入的验证是不同的类似的方法。
所以我必须做以下事情,以确保我不接受像 23 之间的一些糟糕的年代:

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.

推荐答案

我喜欢你使用 try..except 验证输入,因为在某些将来的Python版本中, 1000可能是可以接受的。

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.

该代码中的这个评论表明这个限制仅限于Python当前的strftime实现。

This comment in the code suggests this restriction is limited to Python's current implementation of strftime.

在Python 2.7中, years< 1900 ,但是在Python 3.2中
,则 years < 1000

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)

打印

year=23 is before 1000; the datetime strftime() methods require year >= 1000

这篇关于`datetime.strftime`和`datetime.strptime` interprete%Y不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆