[英]In python how to change date format in a csv?
我正在嘗試使用python將日期格式從30-Jan-02
更改為30.Jan.2002
30-Jan-02
在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")
反復拆包
day, month, year = row[2].split('-')
條件表達式,假設您的日期不會在未來...
year = ('19' if int(year)>17 else '20')+year
替換row
row[2] = '.'.join((day, month, year))
您還可以使用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'
希望這是上述答案的擴展和自我解釋。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.