熊猫从日期时间转换为整数时间戳

Fra*_*Boi 28 python timestamp datetime-conversion pandas

考虑到 python 中的 Pandas 数据框有一个名为timeinteger 类型的列,我可以datetime使用以下指令将其转换为格式。

df['time'] = pandas.to_datetime(df['time'], unit='s')
Run Code Online (Sandbox Code Playgroud)

所以现在列有类似的条目:2019-01-15 13:25:43

将字符串恢复为整数时间戳值(表示从 开始经过的秒数1970-01-01 00:00:00)的命令是什么?

我检查pandas.Timestamp但找不到转换实用程序,我无法使用pandas.to_timedelta它。

这种转换有什么用吗?

Alw*_*nny 28

您可以使用类型转换为 intastype(int)并将其除以10**9得到 unix epoch 开始的秒数。

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)
Run Code Online (Sandbox Code Playgroud)

  • 由于我在除以 `10**9` 后得到一个浮点类型,我认为最好添加另一个强制转换:`res = (pd.to_datetime(df['time'], unit='s').astype( int)/10**9).astype(int)` (3认同)

Ign*_*ier 22

最简单的方法是使用 .value

pd.to_datetime('1970-01-01').value
Run Code Online (Sandbox Code Playgroud)

如果要将其应用于整个列,只需使用.apply

df['time'] = df['time'].apply(lambda x: x.value)
Run Code Online (Sandbox Code Playgroud)


Gri*_*zov 9

还可以使用.view(...)

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']).view(int) // 10 ** 9
print(df_unix_sec)
Run Code Online (Sandbox Code Playgroud)

.astype(int)上面推荐的使用 的强制转换在 pandas 1.3.0 中已被弃用,并会引发警告:

FutureWarning: casting datetime64[ns] values to int64 with .astype(...) is deprecated and will raise in a future version. Use .view(...) instead.
Run Code Online (Sandbox Code Playgroud)


ALo*_*llz 8

使用.dt.total_seconds()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()
Run Code Online (Sandbox Code Playgroud)

输出

0    1.547559e+09
Name: time, dtype: float64
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

58246 次

最近记录:

4 年,8 月 前