Reputation: 1517
I'm running into an issue with Date time in python. Here's my stack trace:
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'
And the relevant bit of code:
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()
As far as I can see, the format string should be correct? This same call to strptime works when inputting the string directly via the terminal.
Any ideas?
Upvotes: 0
Views: 860
Reputation: 1121186
%Y
expects a year with four digits, including the century. Use %y
to parse dates with a 2-digit year.
Demo:
>>> 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
adds a century following the POSIX convention for C strptime
:
%y
The year within century (0-99). When a century is not otherwise specified, values in the range 69-99 refer to years in the twentieth century (1969-1999); values in the range 00-68 refer to years in the twenty-first century (2000-2068).
Upvotes: 4