我遇到了python中的日期时间问题。这是我的堆栈跟踪:
28/09/12
Traceback (most recent call last):
File "product-release-by-year.py", line 49, in <module>
get_earliest_order_date(fin)
File "product-release-by-year.py", line 25, in get_earliest_order_date
date = datetime.datetime.strptime(order_date, '%d/%m/%Y').date()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '28/09/12' does not match format '%d/%m/%Y'
相关的代码:
def get_earliest_order_date(fin):
# CSV Headers
product_col = 1
order_col = 0
f = open(fin, 'rb')
try:
reader = csv.reader(f, delimiter=";")
next(reader, None)
for row in reader:
product_name = row[product_col]
order_date = row[order_col]
print order_date
date = datetime.datetime.strptime(order_date, '%d/%m/%Y').date()
if product_name not in products:
products[product_name] = date
else:
if date < products[product_name]:
products[product_name] = date
finally:
f.close()
据我所知,格式字符串应该是正确的?当通过终端直接输入字符串时,对strptime的同一调用也有效。
有什么想法吗?
答案 0 :(得分:4)
%Y
预计一年有四个数字,包括世纪。使用%y
来解析年份为2位的日期。
演示:
>>> import datetime
>>> order_date = '28/09/12'
>>> datetime.datetime.strptime(order_date, '%d/%m/%Y')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data '28/09/12' does not match format '%d/%m/%Y'
>>> datetime.datetime.strptime(order_date, '%d/%m/%y')
datetime.datetime(2012, 9, 28, 0, 0)
%y
在POSIX convention for C strptime
之后增加了一个世纪:
%y
世纪之内(0-99)。什么时候不是一个世纪 指定的,69-99范围内的值是指二十年中的年份 世纪(1969-1999); 00-68范围内的值是指 二十一世纪(2000-2068)。