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")
Édouard Blondel
  • 11
  • 1
  • 1
  • 3
  • What is the exact problem with your code? Do you get an error message? – MrLeeh May 18 '17 at 10:49
  • What is the problem you facing? – MONTYHS May 18 '17 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(...)``. – Mike Scotty May 18 '17 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 ! – Édouard Blondel May 18 '17 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](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask) – Mike Scotty May 18 '17 at 10:53
  • Maybe because I didnt save my changes , I just relauched it and I got: 'Traceback (most recent call last): File "read_erg_data.py", line 25, in w.writerow(row) File "/Users/edouardblondel/anaconda/lib/python3.6/tempfile.py", line 483, in func_wrapper return func(*args, **kwargs) TypeError: a bytes-like object is required, not 'str'' – Édouard Blondel May 18 '17 at 10:56
  • You have to look at this question... http://stackoverflow.com/questions/14524322/how-to-convert-a-date-string-to-different-format – Swadhikar May 18 '17 at 11:30

3 Answers3

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'  
manvi77
  • 536
  • 1
  • 5
  • 15
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))
gboffi
  • 22,939
  • 8
  • 54
  • 85
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
Swadhikar
  • 2,152
  • 1
  • 19
  • 32