Python时间戳正则表达式

时间:2012-03-09 16:09:55

标签: python timestamp expression

有人帮我处理我的代码,我将csv文件中的数据写入timeStamp列表吗?列表中的数据目前的格式如此03.08.2012 07.11.15 PM。我需要将时间07:11:15放入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

以下是我收到的错误消息:

  

追踪(最近一次通话):         文件“rates.py”,第17行,in           match = regexp.match(timeStamp [x])       TypeError:期望的字符串或缓冲区

2 个答案:

答案 0 :(得分:6)

改为使用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'

答案 1 :(得分:1)

row[7:8]是长度为1的列表,而不是字符串。 regexp需要一个字符串。请改用row[7]