python 用微秒解析日期时间字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/531157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:19:27  来源:igfitidea点击:

Parsing datetime strings with microseconds

pythondatetimeparsing

提问by Manuel Ceron

I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:

我有一个文本文件,其中包含许多 isoformat 格式的日期时间字符串。字符串类似于:

'2009-02-10 16:06:52.598800'

'2009-02-10 16:06:52.598800'

These strings were generated using str(datetime_object). The problem is that, for some reason, str(datetime_object)generates a different format when the datetime object has microseconds set to zero and some strings look like this:

这些字符串是使用str(datetime_object). 问题是,由于某种原因,str(datetime_object)当 datetime 对象将微秒设置为零并且某些字符串如下所示时,会生成不同的格式:

'2009-02-10 16:06:52'

'2009-02-10 16:06:52'

How can I parse these strings and convert them into a datetime object?

如何解析这些字符串并将它们转换为日期时间对象

It's very important to get all the data in the object, including microseconds.

获取对象中的所有数据非常重要,包括微秒。

I have to use Python 2.5, I've found that the format directive %ffor microseconds doesn't exist in 2.5.

我必须使用Python 2.5,我发现%f2.5 中不存在微秒的格式指令。

回答by Eli Bendersky

Alternatively:

或者:

from datetime import datetime

def str2datetime(s):
    parts = s.split('.')
    dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S")
    return dt.replace(microsecond=int(parts[1]))

Using strptimeitself to parse the date/time string (so no need to think up corner cases for a regex).

使用strptime自身来解析日期/时间字符串(因此无需考虑正则表达式的极端情况)。

回答by Soviut

Use the dateutil module. It supports a much wider range of date and time formats than the built in Python ones.

使用 dateutil 模块。与内置的 Python 格式相比,它支持更广泛的日期和时间格式。

You'll need to easy_install dateutilfor the following code to work:

您需要使用easy_install dateutil才能使以下代码正常工作:

from dateutil.parser import parser

p = parser()
datetime_with_microseconds = p.parse('2009-02-10 16:06:52.598800')
print datetime_with_microseconds.microsecond

results in:

结果是:

598799

回答by RSabet

Someone has already filed a bug with this issue: Issue 1982. Since you need this to work with python 2.5 you must parse the value manualy and then manipulate the datetime object.

有人已经提交了一个关于这个问题的错误:问题 1982。由于您需要它与 python 2.5 一起使用,您必须手动解析该值,然后操作 datetime 对象。

回答by David Z

It might not be the best solution, but you can use a regular expression:

这可能不是最好的解决方案,但您可以使用正则表达式:

m = re.match(r'(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(?:\.(\d{6}))?', datestr)
dt = datetime.datetime(*[int(x) for x in m.groups() if x])