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

时间:2019-01-22 16:43:26

标签: python pandas timestamp datetime-conversion

考虑到python中的pandas数据帧具有名为time的整数类型的列,我可以按照以下说明将其转换为datetime格式。

df['time'] = pandas.to_datetime(df['time'], unit='s')

因此,该列现在具有类似2019-01-15 13:25:43的条目。

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

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

此转换有实用程序吗?

4 个答案:

答案 0 :(得分:4)

.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()
# or
(df.time - pd.to_datetime('1970-01-01')).dt.total_seconds()

输出

0    1.547559e+09
Name: time, dtype: float64

答案 1 :(得分:3)

您可以使用astype(int)强制转换为int,然后将其除以10**9,以获取unix纪元开始的秒数。

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)

答案 2 :(得分:1)

按照@Ignacio的建议,这就是我用来转换为整数的内容:

df['time'] = df['time'].apply(lambda x: x.value)

然后,将其取回:

df['time'] = df['time'].apply(pd.Timestamp)

答案 3 :(得分:0)

最简单的方法是使用.value

pd.to_datetime('1970-01-01').value