Python 无法将日期转换为 datetime64

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16158795/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:54:33  来源:igfitidea点击:

Can't convert dates to datetime64

pythonnumpypandas

提问by sashkello

The following piece of code:

下面的一段代码:

import pandas as pd
import numpy as np

data = pd.DataFrame({'date': ('13/02/2012', '14/02/2012')})
data['date'] = data['date'].astype('datetime64')

works fine on one machine (windows) and doesn't work on another (linux). Both numpy and pandas are installed on both.

在一台机器(windows)上工作正常,在另一台机器(linux)上不起作用。两者都安装了 numpy 和 pandas。

The error I get is:

我得到的错误是:

ValueError: Cannot create a NumPy datetime other than NaT with generic units

What does this error mean? I see it for the first time ever and there is not much on the web I can find. Is it some missing dependency?

这个错误是什么意思?我有史以来第一次看到它,我在网上找不到太多东西。是否缺少某些依赖项?

采纳答案by Jeff

Do this instead. Pandas keeps datestimes internally as datetime64[ns]. Conversions like this are very buggy (because of issues in various numpy version, 1.6.2 especially). Use the pandas routines, then operate like thesee are actual datetime objects. What are you trying to do?

改为这样做。Pandas 在内部将日期时间保持为datetime64[ns]. 像这样的转换非常有问题(因为各种 numpy 版本中的问题,尤其是 1.6.2)。使用 Pandas 例程,然后像看到实际日期时间对象一样操作。你想做什么?

In [30]: pandas.to_datetime(data['date'])
Out[30]: 
0   2012-02-13 00:00:00
1   2012-02-14 00:00:00
Name: date, dtype: datetime64[ns]