简体   繁体   中英

Microsecond part lost when converting a date string to a datetime object in python

I have the following date string:

dtstr = '2010-12-19 03:44:34.778000'

I wanted to convert it to a datetime object, so i proceeded as follows:

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)))

But this returned : datetime.datetime(2010, 12, 19, 3, 44, 34) instead of datetime.datetime(2010, 12, 19, 3, 44, 34,778000)

Why did the microsecond part get omitted ?. How can i get datetime.datetime(2010, 12, 19, 3, 44, 34,778000) ?

Please Help Thank You

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 handles seconds since the Unix epoch, so using time loses the microseconds. Use datetime.strptime directly.

The time.struct_time object returned by time.strptime does not store milliseconds:

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)

But the datetime object returned by dt.datetime.strptime does store milliseconds:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM