pandas convert from datetime to integer timestamp
The easiest way is to use .value
pd.to_datetime('1970-01-01').value
If you want to apply it to the whole column, just use .apply
:
df['time'] = df['time'].apply(lambda x: x.value)
As @Ignacio recommends, this is what I am using to cast to integer:
df['time'] = df['time'].apply(lambda x: x.value)
Then, to get it back:
df['time'] = df['time'].apply(pd.Timestamp)
Use .dt.total_seconds()
on a timedelta64
:
import pandas as pd
df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]})
# pd.to_timedelta(df.time).dt.total_seconds() # Is deprecated
(df.time - pd.to_datetime('1970-01-01')).dt.total_seconds()
Output
0 1.547559e+09
Name: time, dtype: float64
You can typecast to int using astype(int)
and divide it by 10**9
to get the number of seconds to the unix epoch start.
import pandas as pd
df = pd.DataFrame({'time': [pd.to_datetime('2019-01-15 13:25:43')]})
df_unix_sec = pd.to_datetime(df['time']).astype(int)/ 10**9
print(df_unix_sec)