'Cannot convert input [00:00:00.020000] of type <class 'datetime.time'> to Timestamp
My input data has a high resolution of datetime with seconds in fraction. For example, it should be 1900-01-01 17:40:14.410000 instead of 1900-01-01 17:40:14.
Apparently this format has not been recognized by the pandas or python. How should I successfully convert this to pandas recognized time stamp style.
Solution 1:[1]
Convert column or scalar to strings:
t = datetime.time(17, 40, 14, 410000)
print (pd.to_datetime(str(t)))
2022-02-09 17:40:14.410000
If column:
pd.to_datetime(df['col'].astype(str))
Solution 2:[2]
IIUC, you want a custom format:
pd.to_datetime('[00:00:00.020000]', format='[%H:%M:%S.%f]')
or, automagically:
pd.to_datetime('[00:00:00.020000]'.strip('[]'))
output: Timestamp('2022-02-09 00:00:00.020000')
As series:
s = pd.Series(['[00:00:00.020000]'])
pd.to_datetime(s.str.strip('[]'))
output:
0 2022-02-09 00:00:00.020
dtype: datetime64[ns]
Solution 3:[3]
I'm not sure if I understand it correctly but pandas do have the style in the Timestamp class,
myTime = pandas.Timestamp("1900-01-01 17:40:14.410000") which you can access the attributes and methods of.
myTime.year should output >>> 1900
myTime.time() should output >>> 17:40:14.410000 so on and so forth.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jezrael |
| Solution 2 | mozway |
| Solution 3 | denizberkin |
