pandas 将日期从 int64 转换为日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45218284/
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
Convert date from int64 to datetime
提问by ATMA
I have an int64 object in a pandas data frame and that is supposed to represent a date.
我在Pandas数据框中有一个 int64 对象,它应该代表一个日期。
>>> df.dtypes
CreatedDate int64
Obviously, I want to convert this into a date time, so I did the following
显然,我想将其转换为日期时间,因此我执行了以下操作
df["CreatedDate2"] = pd.to_datetime(pd.Series(df["CreatedDate"]))
>>> df[["CreatedDate","CreatedDate2"]].head()
CreatedDate CreatedDate2
0 1466461661000 1970-01-01 00:24:26.461661
1 1464210703000 1970-01-01 00:24:24.210703
2 1423576093000 1970-01-01 00:23:43.576093
3 1423611903000 1970-01-01 00:23:43.611903
4 1423617600000 1970-01-01 00:23:43.617600
>>>
However, this is producing dates that are in the 1970s, which shouldn't be true. Can anyone tell me how to convert int64 to datetime in a pandas data frame. I thought this was the right way.
然而,这产生了 1970 年代的日期,这不应该是真的。谁能告诉我如何在 Pandas 数据框中将 int64 转换为日期时间。我认为这是正确的方法。
回答by jezrael
Use parameter unit
in to_datetime
for convert unix epoch time:
使用参数unit
into_datetime
来转换 unix 纪元时间:
df["CreatedDate2"] = pd.to_datetime(df["CreatedDate"], unit='ms')
print (df)
CreatedDate CreatedDate2
0 1466461661000 2016-06-20 22:27:41
1 1464210703000 2016-05-25 21:11:43
2 1423576093000 2015-02-10 13:48:13
3 1423611903000 2015-02-10 23:45:03
4 1423617600000 2015-02-11 01:20:00
回答by EdChum
You need to pass unit='ms'
as they are milliseconds since Unix Epoch:
您需要传递unit='ms'
自 Unix Epoch 以来的毫秒数:
In[51]:
df['CreatedDate2'] = pd.to_datetime(df['CreatedDate'], unit='ms')
df
Out[51]:
CreatedDate CreatedDate2
0 1466461661000 2016-06-20 22:27:41
1 1464210703000 2016-05-25 21:11:43
2 1423576093000 2015-02-10 13:48:13
3 1423611903000 2015-02-10 23:45:03
4 1423617600000 2015-02-11 01:20:00
by default the unit
param is 'ns'
as it assumes datetime64[ns]
values which are nanoseconds since the unix epoch if the passed values are int64
dtype
默认情况下,如果传递的值为dtype ,则unit
param'ns'
假定datetime64[ns]
值为自 unix 纪元以来的纳秒数int64