1

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")
7
  • What is the exact problem with your code? Do you get an error message? Commented May 18, 2017 at 10:49
  • What is the problem you facing? Commented May 18, 2017 at 10:49
  • 1
    If your date is in the second position it should be in row[1]. And if it's in the form 30-Jan-02 then why do you split with /? And when you build your new date you want to use dt instead of row in "{}.{}.{}".format(...). Commented May 18, 2017 at 10:50
  • these are the errors I get : ' AttributeError: 'DataFrame' object has no attribute 'strftime' TypeError: a bytes-like object is required, not 'str'``@MrLeeh @MONTYHS thanks ! Commented May 18, 2017 at 10:53
  • 1
    Your error makes no sense, since you're not calling strftime anywhere in your sample code - and your sample code does not use DataFrame objects either. Please read How to create a Minimal, Complete, and Verifiable example and How do I ask a good question? Commented May 18, 2017 at 10:53

3 Answers 3

2

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'  
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.