如何转换为DateTime

Ren*_*ier 1 python regex csv datetime

我有CSV文件,其中包括日期,看起来像:

2014-01-25 00:14:08.000
Run Code Online (Sandbox Code Playgroud)

现在我解析CSV文件并获取日期.然后我运行一个正则表达式来检查日期是否有效(匹配上面的格式)然后我将日期从CSV文件转换为DateTime.

这怎么能给我一个ValueError:陈述:need more than 3 values to unpack.CSV文件可以包含数千条记录,其日期与上述类似.

我的正则表达式:

date_re_time_norm = re.compile("""^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[ ](\d\d:\d\d:\d\d.\d\d\d)$""", re.I)
Run Code Online (Sandbox Code Playgroud)

我的转换方法:

def convert_date(self, dstring):
    if self.date_re_time_norm.match(dstring):
        year, month, day, hour, minute, second = str(dstring).split('-')
    return datetime(int(year), int(month), int(day), int(hour), int(minute), int(second), 0, 0, 0, 0, 0, 0)
Run Code Online (Sandbox Code Playgroud)

方法缩短了可读性.

难道我做错了什么?

jon*_*rpe 10

使用它会好得多datetime.strptime:

from datetime import datetime

d = datetime.strptime("2014-01-25 00:14:08.000", "%Y-%m-%d %H:%M:%S.%f")
Run Code Online (Sandbox Code Playgroud)

这可以替换两个正则表达式,因为它将以适当的格式解析日期,否则会引发错误:

def convert_date(self, dstring, format="%Y-%m-%d %H:%M:%S.%f"):
    try:
        return datetime.strptime(dstring, format)
    except ValueError:
        # wrong format
Run Code Online (Sandbox Code Playgroud)

(您可以根据需要使格式字符串成为类或实例属性).


编辑:如果你决定坚持使用正则表达式,你需要做更多的分裂:

date, time = dstring.split(" ")
year, month, day = date.split("-")
hour, minute, second = time.split(":")
second = second.split(".")[0]
return datetime(*map(int, (year, month, day, hour, minute, second)))
Run Code Online (Sandbox Code Playgroud)

然而,在Python中,"应该有一个 - 最好只有一个 - 显而易见的方式",这样做strptime.