0

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.

3
  • 1
    try open('newsedit.csv', 'a'). Commented Dec 8, 2016 at 7:45
  • thanks worked like a charm Commented Dec 8, 2016 at 7:51
  • it works, but it is not a good idea :) Commented Dec 8, 2016 at 8:12

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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...)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.