-1

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 ?

user8929822
  • 273
  • 1
  • 3
  • 13
  • possible duplicate https://stackoverflow.com/questions/9507648/datetime-from-string-in-python-best-guessing-string-format – badger0053 Nov 14 '17 at 05:19
  • Possible duplicate of [datetime from string in Python, best-guessing string format](https://stackoverflow.com/questions/9507648/datetime-from-string-in-python-best-guessing-string-format) – E_net4 Nov 15 '17 at 11:22

1 Answers1

-2

Example using dateutil

from dateutil.parser import *

dates = ["2005","2006","4 March 2013","5 April 2012","14th February 2012","7th 
January 2014","April 10, 2014","March 3, 2017","October 1st, 1943","Dec 23rd, 
1978"]

for date in dates:
  print(dateutil.parser.parse(date))
badger0053
  • 1,179
  • 1
  • 13
  • 19
  • This answer is the same as the answer in the tagged duplicate question. Please tag this question as duplicate of that, instead of duplicating the answer here. – Vivek Kumar Nov 14 '17 at 05:53
  • Thank you for reaching out. I executed your code in PyCharm. The output I received is as follows: 2005-11-14 00:00:00 2006-11-14 00:00:00 2013-03-04 00:00:00 2012-04-05 00:00:00 2012-02-14 00:00:00 2014-01-07 00:00:00 2014-04-10 00:00:00 2017-03-03 00:00:00 1943-10-01 00:00:00 1978-12-23 00:00:00 I was looking for an output as shown below. YYYY: 2005 2006 DD MonthName YYYY: 4 March 2013 5 April 2012 MonthName DD, YYYY: April 10, 2014 March 3, 2017 Is there a way I could do something like this ? Thanks. – user8929822 Nov 14 '17 at 18:58