priya
priya

Reputation: 375

Extract milliseconds from datetimeobject

I have timestamp like this, 1581584236812954845 and i tried to extract milliseconds alone

df['time'] =pd.to_datetime(df['timestamp'])
df['time'] =df['time'].dt.strftime(("%Y-%m-%d %H:%M:%S.%f") [:-3])

But i only got 08:57:16. At the end i want output as 0.812 from 08:57:16.812954845

Upvotes: 0

Views: 130

Answers (1)

FObersteiner
FObersteiner

Reputation: 25594

try using the str accessor:

import pandas as pd
s = pd.to_datetime(pd.Series([1581584236812954845]))

s.dt.strftime("%Y-%m-%d %H:%M:%S.%f").str[:-3]
# or simpler: s.astype(str).str[:-3]
0    2020-02-13 08:57:16.812
dtype: object

Side note: in your code,

("%Y-%m-%d %H:%M:%S.%f")[:-3]
Out[54]: '%Y-%m-%d %H:%M:%S'

...is why you get e.g. 08:57:16. I suggest having another look at where exactly to place which bracket.

Upvotes: 1

Related Questions