Python 熊猫从日期时间转换为整数时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54312802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas convert from datetime to integer timestamp
提问by Francesco Boi
Considering a pandas dataframe in python having a column named time
of type integer, I can convert it to a datetime
format with the following instruction.
考虑到 python 中的 Pandas 数据框有一个名为time
integer 类型的列,我可以datetime
使用以下指令将其转换为格式。
df['time'] = pandas.to_datetime(df['time'], unit='s')
so now the column has entries like: 2019-01-15 13:25:43
.
所以现在列有类似的条目:2019-01-15 13:25:43
。
What is the command to revert the string to an integer timestamp value (representing the number of seconds elapsed from 1970-01-01 00:00:00
)?
将字符串恢复为整数时间戳值(表示从 开始经过的秒数1970-01-01 00:00:00
)的命令是什么?
I checked pandas.Timestamp
but could not find a conversion utility and I was not able to use pandas.to_timedelta
for this.
我检查pandas.Timestamp
但找不到转换实用程序,我无法使用pandas.to_timedelta
它。
Is there any utility for this conversion?
这种转换有什么用吗?
回答by Always Sunny
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.
您可以使用类型转换为 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)
回答by ALollz
Use .dt.total_seconds()
on a timedelta64
:
使用.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()
Output
输出
0 1.547559e+09
Name: time, dtype: float64
回答by Ignacio Peletier
The easiest way is to use .value
最简单的方法是使用 .value
pd.to_datetime('1970-01-01').value