2017-05-18 254 views
0

我想改變日期的格式從30-Jan-0230.Jan.2002發生在使用python的csv文件的第二個位置。 我嘗試了幾件事情,但我很困惑與字符串和字節compability。在python中如何更改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

什麼是你的代碼確切的問題?你有錯誤信息嗎? – MrLeeh

+0

您面臨的問題是什麼? – MONTYHS

+1

如果你的日期在第二個位置,它應該在''row [1]''中。如果它的格式是''30-Jan-02'',那你爲什麼要用''/''來分割?當你建立新的日期時,你想在'''{}。{}。{}。。format(...)''中使用''dt''而不是''row''。 –

回答

1

迭代拆包

day, month, year = row[2].split('-') 

條件表達式,假設你的日期將不會走向未來......

year = ('19' if int(year)>17 else '20')+year 

更換成row

row[2] = '.'.join((day, month, year)) 
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' 
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