我有以下日期字符串:
dtstr = '2010-12-19 03:44:34.778000'
我想将它转换为日期时间对象,所以我继续如下:
import time
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
datetime.fromtimestamp(time.mktime(time.strptime(dtstr,format)))
但是返回了:datetime.datetime(2010, 12, 19, 3, 44, 34)
而不是datetime.datetime(2010, 12, 19, 3, 44, 34,778000)
为什么微秒部分被省略?我如何获得datetime.datetime(2010, 12, 19, 3, 44, 34,778000)
?
请帮助 谢谢
答案 0 :(得分:7)
from datetime import datetime
dtstr = '2010-12-19 03:44:34.778000'
format = "%Y-%m-%d %H:%M:%S.%f"
a = datetime.strptime(dtstr,format)
print a.microsecond
time
处理自Unix纪元以来的秒数,因此使用time
会丢失微秒。直接使用datetime.strptime
。
答案 1 :(得分:2)
time.struct_time
返回的time.strptime
对象不存储毫秒:
In [116]: time.strptime(dtstr,"%Y-%m-%d %H:%M:%S.%f",)
Out[116]: time.struct_time(tm_year=2010, tm_mon=12, tm_mday=19, tm_hour=3, tm_min=44, tm_sec=34, tm_wday=6, tm_yday=353, tm_isdst=-1)
但是dt.datetime.strptime
返回的datetime对象确实存储了毫秒:
In [117]: import datetime as dt
In [118]: dt.datetime.strptime(dtstr,"%Y-%m-%d %H:%M:%S.%f")
Out[118]: datetime.datetime(2010, 12, 19, 3, 44, 34, 778000)