python datetime.strptime: ignore fraction of a second
The directive %f
will interpret fractional seconds: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
import datetime
humanTime = '2012/06/10T16:36:20.509Z'
datetime.datetime.strptime(humanTime, '%Y/%m/%dT%H:%M:%S.%fZ')
>> datetime.datetime(2012, 6, 10, 16, 36, 20, 509000)
Pandas can also parse the string with fractional seconds...
import pandas as pd
humanTime = '2012/06/10T16:36:20.509Z'
pd.to_datetime(humanTime)
>> Timestamp('2012-06-10 16:36:20.509000+0000', tz='UTC')
Since I really don't care about the fractions of a second, I should just take the first 19
characters of the human readable string, and apply a simple format on that.
>>> humanTime = '2012/06/10T16:36:20.509Z'
>>> datetime.datetime.strptime(humanTime[:19], "%Y/%m/%dT%H:%M:%S")
datetime.datetime(2012, 6, 10, 16, 36, 20)
Solution to your particular problem: use the %f for microseconds:
>>> datetime.datetime.strptime(humanTime, "%Y/%m/%dT%H:%M:%S.%fZ")
However, the problem is still there for a general case. If you'd have more than 6 digits after the dot, then this solution won't work.
The problem is that, to my knowledge, datetime.datetime.strptime accepted formats don't include floating seconds in general. The workaround is to ignore seconds when creating your datetime variable and afterwards add the seconds with datetime.timedelta.
>>> import numpy as np
>>> import datetime
>>>
>>> humanTime = '2012/06/10T16:36:20.509Z'
>>> dt_time_no_seconds = datetime.datetime.strptime(humanTime[:-8], "%Y/%m/%dT%H:%M")
>>> seconds = np.float(humanTime[-7:-1])
>>> dt_time = dt_time_no_seconds+datetime.timedelta(seconds=seconds)
>>> dt_time_no_seconds
datetime.datetime(2012, 6, 10, 16, 36)
>>> dt_time
datetime.datetime(2012, 6, 10, 16, 36, 20, 509000)
Hope this helps.