kimpster
kimpster

Reputation: 77

Changing to MYSQL compliant date format using python

I currently have a csv file containing a column of dates that is formatted as dd/mm/yyyy but i want to change it to yyyy/mm/dd

I have written the code below:

import csv
csv_in = open('news.csv','rb')

for rows in csv.reader(csv_in):
    value = rows[0]
    day= value[:2]
    year= value[-4:]
    month= value[3:5]
    edited = year +'/'+month+'/'+day
    rows[0] = edited
    writer =csv.writer(open('newsedit.csv', 'wb'))
    writer.writerow(rows)

for some reason the code above will only write one row and stop and i can't seem to figure out why this is happening.

Upvotes: 0

Views: 532

Answers (2)

ichbinblau
ichbinblau

Reputation: 4799

Try convert the date by datetime module.

import datetime
datetime.datetime.strptime("25/01/2013", '%d/%m/%Y').strftime('%Y/%m/%d')

The strptime function loads a string to datetime object while strftime converts the datetime to another format as string.

Upvotes: 1

SheepPerplexed
SheepPerplexed

Reputation: 1152

It is because you keep initializing a new writer in each iteration. This causes that the output is being replaced over and over again. You should create a writer object only once, then you can use its writerow() method repeatedly.

(Btw. there is a nice datetime module that makes working with dates easy...)

Upvotes: 1

Related Questions