cftime.DatetimeNoLeap 对象无法使用 pandas.to_datetime() 转换

cftime.DatetimeNoLeap object fails to convert with pandas.to_datetime()

我正在使用 xarray 读取多个气候模型数据,自从升级 python 我的代码现在已停止工作。

由于某些模型数据具有不同的日历,它正在崩溃:

In [15]: ds.coords['time'].values[0]
Out[15]: cftime.DatetimeNoLeap(1861, 1, 16, 12, 0, 0, 0, 0, 16)

这意味着 pandas.to_datetime() 失败:

pd.to_datetime(ds.coords['time'].values[0])
TypeError: <type 'cftime._cftime.DatetimeNoLeap'> is not convertible to datetime

有办法解决这个问题吗?

xaray 最近发生了变化,以更好地支持非标准日历。 xarray 文档中有一整节描述了这些更改以及如何恢复以前的行为 (link to docs)。

我认为在你的情况下,如果你想将你的时间值转换为标准的完整 Pandas 日期时间,你可以简单地使用 to_datetimeindex() 方法:

ds.indexes['time'].to_datetimeindex()