Python Strptime formatting



我遇到了python中Date时间的问题。下面是我的堆栈跟踪:

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的调用也同样有效。

任何想法?

%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在C strptime的POSIX约定之后增加了一个世纪:

%y
世纪内年份(0-99)。当一个世纪没有其他69 ~ 99之间的取值表示后20年的年份世纪(1969 - 1999);00-68表示21世纪的年代(2000-2068)。

相关内容

  • 没有找到相关文章

最新更新