Reputation: 33
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
Upvotes: 3
Views: 1016
Reputation: 879749
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)
Upvotes: 2
Reputation: 176800
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.
Upvotes: 7