问题描述
我有一个文本文件,其中包含许多同格式的日期时间字符串.字符串与此类似:
I have a text file with a lot of datetime strings in isoformat. The strings are similar to this:
'2009-02-10 16:06:52.598800'
这些字符串是使用 str(datetime_object)
生成的.问题是,由于某种原因,当datetime对象的微秒设置为零且某些字符串如下所示时, str(datetime_object)
会生成不同的格式:
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:
'2009-02-10 16:06:52'
如何解析这些字符串并将其转换为 datetime对象?
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.
注意:我必须使用 Python 2.5 ,2.5秒中不存在格式指令%f
微秒.
NOTE: I have to use Python 2.5, the format directive %f
for microseconds doesn't exist in 2.5.
推荐答案
或者:
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]))
使用 strptime
本身来解析日期/时间字符串(因此无需考虑正则表达式的特殊情况).
Using strptime
itself to parse the date/time string (so no need to think up corner cases for a regex).
这篇关于在Python 2.5中以微秒为单位解析日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!