Python strptime解析年无世纪:假设在今年之前? [英] Python strptime parsing year without century: assume prior to this year?
本文介绍了Python strptime解析年无世纪:假设在今年之前?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 datetime.strptime
在Python 2.7中解析一些日期时间字符串。我想假设一个日期早于现在。
I am parsing some datetime strings in Python 2.7, using datetime.strptime
. I want to assume that a date is prior to now.
但是strptime的 %y
运算符默认情况下不会执行此操作:
But strptime's %y
operator does not do this by default:
d = '10/12/68'
n = datetime.strptime(d, '%d/%m/%y')
print n
2068-12-10 00:00:00
有什么方法可以让Python假定 68
是 1968
,因为它很常见?
Is there any way I can get Python to assume that 68
is 1968
, as it would be in common usage?
还是我应该只解析字符串并酌情手动插入 19
或 20
吗?
Or should I just parse the string and insert 19
or 20
, as appropriate, manually?
推荐答案
以下事实很容易解决:
from datetime import datetime, timedelta
dt = datetime.strptime(...)
if dt > datetime.now():
dt -= timedelta(years=100)
这篇关于Python strptime解析年无世纪:假设在今年之前?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文