0

I need to exchange dateformats in a large csv from DD/MM/YYYY to YYYY-MM-DD. I have no problem printing out the values I want them to replace with, but I have a hard time actually overwriting the csv.

Here is my code:

import csv
from datetime import datetime

with open('partner_new_testteam.csv', newline='') as data:
    reader = csv.reader(data)

    for list in reader:
        for string in list:
            try:
                datetimeobject = datetime.strptime(string, '%d/%m/%Y')
                changedDate = datetimeobject.strftime('%Y-%m-%d')
                print(changedDate)

            except:
                continue

I know this code is rather sloppy, but keep in mind that I just started programming, thanks in advance!

0

3 Answers 3

2
import csv
import re
from datetime import datetime

lines = []
# open file as read-only
with open('partner_new_testteam.csv', "r", newline='') as data:
    reader = csv.reader(data)
    # go over all of its rows, and the row's items and change 
    # items that match the date format
    for row in reader:
        for i, string in enumerate(row):
            if re.match(r"\d+\/\d+\/\d+", string):
                datetimeobject = datetime.strptime(string, '%d/%m/%Y')
                new_string = datetimeobject.strftime('%Y-%m-%d')
                row[i] = new_string
                print("Replaced", string, "with", new_string)
        # save edited, and originally correct ones to new list
        new_row = row
        lines.append(new_row)

# write new rows by overwriting original file
with open('partner_new_testteam.csv', "w", newline='') as data:
    writer = csv.writer(data)
    writer.writerows(lines)

Your current code does not actually change anything. You never replaced anything and you didn't open the file with write access.

You also should not use try: like it is an if. The regex matches x/x/x, where x is any amount of numbers.

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

1 Comment

It worked thanks a mill!! Another question... It makes sense when I see your code now, but if I had to do it myself I would be completely lost. Is that something that comes just with experience?
0

The .csv file is opened read-only per your 'open' command.

You need to pass the 'w' parameter to the 'open' command.

Comments

0

read csv using pandas -> pd.read_csv and then use pd.to_datetime

eg.

data = pd.DataFrame()

data['A'] = ['11/12/2018']

print(data)

            A
0  11/12/2018

using pd.to_datetime

data.A = pd.to_datetime(data['A'])

print(data)

           A
0 2018-11-12

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.