The Shed is going Social! Join us on FaceBook and Twitter and chime in on the conversation.
|
 |
|
Dev Shed Forums
> Programming Languages
> Python Programming
|
String replacement question
Discuss String replacement question in the Python Programming forum on Dev Shed. String replacement question Python Programming forum discussing coding techniques, tips and tricks, and Zope related information. Python was designed from the ground up to be a completely object-oriented programming language.
|
|
 |
|
|
|
|

Dev Shed Forums Sponsor:
|
|
|

July 25th, 2004, 11:55 AM
|
|
Registered User
|
|
Join Date: Jul 2004
Posts: 1
Time spent in forums: < 1 sec
Reputation 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,
|

July 25th, 2004, 06:16 PM
|
|
Contributing User
|
|
Join Date: Feb 2004
Location: London, England
|
|
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.
|

July 25th, 2004, 06:30 PM
|
|
Contributing User
|
|
Join Date: Feb 2004
Location: London, England
|
|
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
|
Developer Shed Advertisers and Affiliates
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Rate This Thread |
Linear Mode
|
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|