【问题标题】:Is there a built-in way to convert datetimes to cftime in xarray?是否有内置方法可以将日期时间转换为 xarray 中的 cftime?
【发布时间】:2022-07-25 19:36:18
【问题描述】:

我想绘制两个时间序列,其中一个在 cftime 中,另一个在 datetime 中。

一种可能性是convert cftime to 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)]

【问题讨论】:

    标签: python datetime python-xarray


    【解决方案1】:

    您确实可以考虑为此使用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
    

    此方法是 xarray 版本 0.20.0 的新方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-21
      • 2010-09-22
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      相关资源
      最近更新 更多