|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
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
|
|||
|
|||
|
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. |
|
#3
|
|||
|
|||
|
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 |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > String replacement question |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|