chu*_*axr 5 python datetime python-xarray
我想绘制两个时间序列,其中一个在 cftime 中,另一个在 datetime 中。
一种可能性是将cftime 转换为 datetime,但这可能会给非标准 cftime 日历(例如 NoLeap)带来奇怪的结果。因此,我正在尝试将日期时间转换为 cftime。
我可以按如下方式暴力破解它,但是有可用的内置方法吗?
>>> import pandas as pd
>>> import xarray as xr
>>>
>>> da = xr.DataArray(
... [1, 2], coords={"time": pd.to_datetime(["2000-01-01", "2000-02-02"])}, dims=["time"]
... )
>>> print(da.time)
<xarray.DataArray 'time' (time: 2)>
array(['2000-01-01T00:00:00.000000000', '2000-02-02T00:00:00.000000000'],
dtype='datetime64[ns]')
Coordinates:
* time (time) datetime64[ns] 2000-01-01 2000-02-02
>>>
>>>
>>> import cftime
>>>
>>>
>>> def datetime_to_cftime(dates, kwargs={}):
... return [
... cftime.datetime(
... date.dt.year,
... date.dt.month,
... date.dt.day,
... date.dt.hour,
... date.dt.minute,
... date.dt.second,
... date.dt.microsecond,
... **kwargs
... )
... for date in dates
... ]
...
>>> datetime_to_cftime(da.time)
[cftime.datetime(2000, 1, 1, 0, 0, 0, 0, calendar='standard', has_year_zero=False), cftime.datetime(2000, 2, 2, 0, 0, 0, 0, calendar='standard', has_year_zero=False)]
Run Code Online (Sandbox Code Playgroud)
事实上,您可能会考虑使用DataArray.convert_calendar. 例如,如果您想将datetime64值转换为cftime.DatetimeNoLeap对象,您可以执行以下操作:
>>> da.convert_calendar("noleap")
<xarray.DataArray (time: 2)>
array([1., 2.])
Coordinates:
* time (time) object 2000-01-01 00:00:00 2000-02-02 00:00:00
Run Code Online (Sandbox Code Playgroud)
此方法是 xarray 版本 0.20.0 中的新方法。