简体   繁体   中英

In python how to change date format in a csv?

I am trying to change the format of dates from 30-Jan-02 to 30.Jan.2002 occurring in second position in a csv file using python. I tried several things but I am confused with strings and bytes comptability.

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")

iterable unpacking

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

conditional expression, assuming your dates won't be into the future...

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

replacing into row

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

You can also use 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'  

Hope this is an extension to above mentioned answer and self explanatory.

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!")

Input: filename.csv

30-Jan-02,31-Jan-02,01-Feb-02
30-Jan-02,31-Jan-02,01-Feb-02

Output: temp.csv

30-Jan-02,31.Jan.2002,01-Feb-02
30-Jan-02,31.Jan.2002,01-Feb-02

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM