我需要将大型格式的日期格式从DD / MM / YYYY交换为YYYY-MM-DD。 我可以打印出要替换的值,但没有困难,但是实际上很难覆盖csv。
这是我的代码:
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
我知道这段代码相当草率,但是请记住,我刚刚开始编程,请先感谢!
答案 0 :(得分:1)
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)
您当前的代码实际上并未更改任何内容。您从来没有替换过任何东西,也没有使用写入权限打开文件。
您也不应使用try:
,因为它是if
。正则表达式匹配x / x / x,其中x是任意数量的数字。
答案 1 :(得分:0)
.csv文件根据您的“打开”命令以只读方式打开。
您需要将'w'参数传递给'open'命令。
答案 2 :(得分:0)
使用pandas
-> pd.read_csv
阅读csv,然后使用pd.to_datetime
例如
data = pd.DataFrame()
data['A'] = ['11/12/2018']
打印(数据)
A
0 11/12/2018
使用pd.to_datetime
data.A = pd.to_datetime(data['A'])
打印(数据)
A
0 2018-11-12