Reputation: 11
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!
Upvotes: 0
Views: 2057
Reputation: 165
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.
Upvotes: 2
Reputation: 3770
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
Upvotes: 0
Reputation: 1
The .csv file is opened read-only per your 'open' command.
You need to pass the 'w' parameter to the 'open' command.
Upvotes: 0