Converting Object(8 digits) to datetime in python

Viewed 45

I have a dataframe. There are several time-related columns in it. They are displayed like Unix time, but they are not exactly!!

Example: I have 18052508 as a TotalTime,

119628 as LapTime

the LapTime makes sense to be 1m.19sec.628 however the 18052508 should be something around five hours plus.

How can I convert them to right time. I need them later for plotting and filtering

I tried

pd.to_datetime(df_stx['TotalTime'],unit='ms').dt.strftime('%H:%M:%S:%f').str[:-3] 

pd.to_datetime(df_stx['TotalTime'],unit='ms') 


pd.to_datetime(data['TotalTime'])
data['TotalTime'].dt.strftime("%H:%M:%S") 


pd.to_datetime(df_stx['TotalTime'])
# this line changed the 18052508 to
1970-01-01 00:00:00.018052508

non of them gave me anything right.or they look fine at begging but when comes to plotting they won't work.

1 Answers

(example to my comment) given you have something like

df = pd.DataFrame({"LapTime": [119628],
                   "TotalTime": [18052508]})

you'd convert to timedelta like

df["LapTime"] = pd.to_timedelta(df["LapTime"], unit="ms")
df["TotalTime"] = pd.to_timedelta(df["TotalTime"], unit="ms")

to get

df
                 LapTime              TotalTime
0 0 days 00:01:59.628000 0 days 05:00:52.508000

Now you can filter/select for example like

df.loc[df["LapTime"]<pd.Timedelta(minutes=3), "TotalTime"]
0   0 days 05:00:52.508000
Name: TotalTime, dtype: timedelta64[ns]
Related