2

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

1
  • In timeStamp.append(row[7:8]) you are appending lists containing exactly one element to the timeStamp list. Afterwards you pass this list to regexp.match(), which expects a string, not a list. Did you mean: timeStamp.append(row[7])? Commented Mar 9, 2012 at 16:13

2 Answers 2

6

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'
Sign up to request clarification or add additional context in comments.

Comments

1

row[7:8] is a list of length 1, not a string. regexp needs a string. Use row[7] instead.

2 Comments

How would I add just the time into a new list? For example I only want 07:11:15 PM in a new list. Thank you.
Different question, right? Depends on what your timestamp looks like. You can probably get it with stamp[:11] (e.g. row[7][:11])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.