I am reading a column from a csv file that contains dates in different formats.
I am trying to write each unique date format to a text file. Some examples of the unique data formats are shown below.
2006
09/12/12
12-24-07
April 10, 2013
29 April 1993
September 2011
March 7
1830s
Friday, 12 February 2010
Thursday, April 19
12th May 2011
413 BC
My Code:
from datetime import datetime
import csv
with open('train.csv', 'rb') as f_input, open('sample.txt', 'wb') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
header = next(csv_input)
for row in csv_input:
for date_format in ['%Y','%m/%d/%y']:
try:
converted = datetime.strptime(row[3], date_format)
csv_output.writerow([row[0], row[1], converted.strftime(date_format)])
except ValueError:
pass
Now, I have figured out the first two formats so far in the line: for date_format in ['%Y','%m/%d/%y']:
I am now sure how the other formats are going to be translated. Any suggestions ?