我正在尝试使用python将日期格式从30-Jan-02
更改为30.Jan.2002
在csv文件中的第二个位置。
我尝试了几件事,但我对字符串和字节的可兼容性感到困惑。
import os
import csv
from datetime import datetime
import sys
from tempfile import NamedTemporaryFile
with open("Filenamecsv",'r') as csvfile, NamedTemporaryFile(dir="path/parh",delete=False) as temp:
w = csv.writer(temp)
r = csv.reader(csvfile)
for row in r:
dt = row[2].split("-")
row[2] = "{}.{}.{}".format(row[-1],row[1],row[0])
w.writerow(row)
move(temp.name,"Filename.csv")
答案 0 :(得分:1)
iterable unpacking
day, month, year = row[2].split('-')
条件表达式,假设您的日期不会在将来......
year = ('19' if int(year)>17 else '20')+year
替换为row
row[2] = '.'.join((day, month, year))
答案 1 :(得分:1)
您也可以使用datetime
In [25]: import datetime
In [26]: dt = datetime.datetime.strptime("30-Jan-02", '%d-%b-%y').strftime('%d.%b.%Y')
In [27]: dt
Out[27]: '30.Jan.2002'
答案 2 :(得分:0)
希望这是对上述答案和自我解释的延伸。
import datetime
with open("filename.csv", 'r') as csvfile, open('temp.csv', 'w') as temp_file:
for line in csvfile.readlines():
# Fetch all dates in the csv
dates = line.split(',')
# Extract date, month and year
dt, mon, yr = dates[1].split('-')
# Convert the second date and replace
dates[1] = datetime.datetime.strptime(dates[1], '%d-%b-%y').strftime('%d.%b.%Y')
# Write date to temp file
temp_file.write(','.join(dates))
print("Process complete!")
输入:filename.csv
30-Jan-02,31-Jan-02,01-Feb-02
30-Jan-02,31-Jan-02,01-Feb-02
输出:temp.csv
30-Jan-02,31.Jan.2002,01-Feb-02
30-Jan-02,31.Jan.2002,01-Feb-02