Sunny
Sunny

Reputation: 99

Issue converting Date to Timestamp using Unix

I have a date.csv file with different dates and I am not able to convert it into a time stamp. e.g.

date.csv has the following dates:-

Mar 24 2014
Apr 1 2014
Aug 25 2014

I am trying to convert the above dates to:-

03/24/2014 00:00:00
04/01/2014 00:00:00
08/25/2014 00:00:00

i.e. in mm/dd/yyyy 00:00:00 format, thereby storing the output in a new file i.e. date1.csv.

How can I do this?

Upvotes: 0

Views: 77

Answers (1)

bjmc
bjmc

Reputation: 3282

You can use the GNU date utility to perform the conversion:

date +"%m/%d/%Y %H:M:%S" -d "Mar 24 2014"
03/24/2014 00:00:00

The question doesn't specify what tools you can use, but this is a basic solution in Python that handles reading in the CSV file, converting the dates, and outputting it to another CSV file:

#!/usr/bin/python

import csv
from datetime import datetime
import sys

DATE_COLUMN = 3 # Or whatever column has the date

input_file = sys.argv[1]
output_file = sys.argv[2]

with open(input_file) as i_f:
    reader = csv.reader(i_f)
    with open(output_file, 'w') as o_f:
        writer = csv.writer(o_f)
        for row in reader:
            date = datetime.strptime(row[DATE_COLUMN], "%h %d %Y")
            row[DATE_COLUMN] = date.strftime("%m/%d/%Y %H:M:%S")
            writer.writerow(row)

Usage:

python csv_date_converter.py input_file output_file

Upvotes: 1

Related Questions