有人可以帮我处理我的代码,我已经将 csv 文件中的数据写入时间戳列表吗?列表中的数据当前格式为 03.08.2012 07.11.15 PM。我需要将时间 07:11:15 PM 放入 actTime
数组中。这是我的代码:
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
这是我收到的错误消息:
Traceback (most recent call last): File "rates.py", line 17, in match = regexp.match(timeStamp[x]) TypeError: expected string or buffer
最佳答案
使用 built-in timestamp parsing mechanism相反。
>>> 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'
关于Python 时间戳正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9637272/