Python 时间戳正则表达式

标签 python timestamp expression

有人可以帮我处理我的代码,我已经将 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/

相关文章:

python - 使用 pandas.io.sql 将列值传递到 SQL 查询的选择中

python - Django 和 MySQL - 无法打开数据库文件

java - 时间戳格式添加 17 小时

python - 如何在 Django 中获取具有反向关系的所有类的集合?

MySQL选择查询具有相同时间的日期范围

arrays - Flash AS3,如何使用整数键索引 HashMap

.net - 以Func体参数唯一标识匿名方法

c# - winforms datagridview计算字段更改事件

r - 在 R 中组合表达式

python - 为什么循环中的 dict.pop() 会从 future 循环迭代中创建的字典中删除键?