#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2004
    Posts
    1
    Rep Power
    0

    String replacement question


    Hello,

    Very new to programming/Python.

    Have a input file with records in the following CSV format
    a,b,c,27 June 10:30 2004,d,e

    Need to process each line and change the date format and insert time record before outputing to new file
    a,b,c,27/06/04,10:30,d,e

    Hopefully someone can point me in the right direction, I'm happy with the file handling bit, its the string replacement bit i need advice on.

    Thanks,
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    If you are using Python 2.3 or later, then it has a CSV module included in the standard library. This includes reader objects to take a string in CSV format and convert it to a list of strings, and writer objects to take a list of strings and convert it to a line in a CSV file. So your code could be something like:

    Code:
    ####untested code - treat with caution
    
    import csv
    
    infile = open('input.csv', 'rb')
    outfile = open('output.csv', 'wb')
    
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    
    
    for line in reader:
        date, time = convertTime(line[3])
        line[3:4] = [date, time]
        writer.writerow(line)
    Where convertTime() is a function you will need to write to convert the date format into a tuple containing the date and the time.

    Dave - The Developers' Coach
    Last edited by DevCoach; July 25th, 2004 at 06:20 PM.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Feb 2004
    Location
    London, England
    Posts
    1,585
    Rep Power
    1373
    For the convertTime function you can use the time module's strftime and strptime functions to parse the date/time string in one format and write it out in a different format:

    Code:
    import time
    
    def convertTime(oldFormat):
        t = time.strptime(oldFormat, '%d %B %H:%M %Y')
        newDate = time.strftime('%d/%m/%y', t)
        newTime = time.strftime('%H:%M', t)
        return (newDate, newTime)
    Dave - The Developers' Coach

    Comments on this post

    • dacash agrees

IMN logo majestic logo threadwatch logo seochat tools logo