Reputation: 1265
Can someone help me with my code where I have written data from a csv file into the timeStamp list? The data in the list is currently formatted like so 03.08.2012 07.11.15 PM. And I need the just the time 07:11:15 PM to be put into the actTime
array. Here is my code:
import csv
import re
reader = csv.reader(open('main.csv','rb'), delimiter=',',quotechar="'")
timeStamp = []
ask = []
regexp = re.compile('\d{2}:\d{2}:\d{4}')
actTime = []
x = 0
try:
for row in reader:
ask.append(row[5:6])
timeStamp.append(row[7:8])
except csv.Error, e:
sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))
for item in timeStamp:
actTime.append(timeStamp[x])
match = regexp.match(timeStamp[x])
if match:
time = int(match.group[x])
x = x + 1
Here is the error message I am getting:
Traceback (most recent call last): File "rates.py", line 17, in match = regexp.match(timeStamp[x]) TypeError: expected string or buffer
Upvotes: 2
Views: 2573
Reputation: 123772
Use the built-in timestamp parsing mechanism instead.
>>> import datetime
>>> t = "03.08.2012 07.11.15 PM"
>>> u = datetime.datetime.strptime(t, "%d.%m.%Y %I.%M.%S %p")
>>> u
datetime.datetime(2012, 8, 3, 19, 11, 15)
>>> u.strftime("%I:%M:%S %p")
'07:11:15 PM'
Upvotes: 6
Reputation: 50220
row[7:8]
is a list of length 1, not a string. regexp
needs a string. Use row[7]
instead.
Upvotes: 1