user3062459
user3062459

Reputation: 1631

Convert CSV column format from string to datetime

Python 3.4 ... I am trying to convert a specific column in CSV from string to datetime and write it to the file. I am able to read and convert it, but need help writing the date format change to the file (the last line of code - needs to be modified). I got the following error for last line of code Error: sequence expected.

import csv
import datetime

with open ('/path/test.date.conversion.csv') as csvfile:
    readablefile = csv.reader(csvfile)
    writablefile = csv.writer(csvfile)
    for row in readablefile:
        date_format = datetime.datetime.strptime(row[13], '%m/%d/%Y')
        writablefile.writerow(date_format)

Upvotes: 0

Views: 10264

Answers (1)

fivetentaylor
fivetentaylor

Reputation: 1297

So date_format is an instance of the datetime class. You need to format a string to print out to file. You can go with the standard:

date_format.isoformat()

Or customize your own format:

date_format.strftime('%Y-%m-%d %H:%M:%S')

Also a couple more things to note. You can't write to the same file you're reading from like that. If you want to overwrite that file, create a tmp file then replace it when done, but it's better to just create another file. The best solution imho is to make good use of stdin and stdout like this:

import csv
import sys
from datetime import datetime

FIELD = 13
FMT = '%m/%d/%Y'

readablefile = csv.reader(sys.stdin)
writablefile = csv.writer(sys.stdout)
for row in readablefile:
    dt = datetime.strptime(row[FIELD], FMT)
    row[FIELD] = dt.isoformat()
    writablefile.writerow(row)

Now you can call the script like so:

cat /path/test.date.conversion.csv | python fixdate.py > another_file.csv

At this point, you can make use of the argparse module to provide all kinds of nice parameters to your script like:

  • Which field to format?
  • What input and/or output format?
  • etc.

Upvotes: 3

Related Questions