qwww
qwww

Reputation: 1363

How to convert a dataframe column to date-time format to plot a timeseries

I have a column in my dataframe with values similar to this

"2017-09-27 06:32:27:919"

I tried to convert it to datetime using pandas to_datettime function. But it is not getting converted. What has to be done?I gave unit='ns' still it is not getting converted.

Upvotes: 0

Views: 76

Answers (1)

gyoza
gyoza

Reputation: 2152

The last : is causing the issue. Replace it with . prior to the convert.

Assuming your time column is df.time,

df['ns'] = df.time.apply(lambda x: x[-3:]) #make up ns column
df.time = df.time.apply(lambda x: str(x)[:-4] + ".") # cut off ns and replace ":" with "."
df.time = df.time + df.ns # combine above 2
df.drop('ns', axis=1, inplace=True) # we no longer need "ns" column
df.time = pd.to_datetime(df.time, unit='ns') # Now you can convert time to "ns"

Upvotes: 1

Related Questions