You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取xarray.DataArray对象中的时间字符串值?

提取xarray DataArray中的时间字符串值

你需要从xarray.core.dataarray.DataArray类型的time对象中提取类似'2010-01-01T00:00:00.000000000'格式的时间字符串,你的time对象结构如下:

>>> type(time)
<class 'xarray.core.dataarray.DataArray'>

>>> time
<xarray.DataArray 'time' (time: 65)>
array(['2010-01-01T00:00:00.000000000', '2010-01-01T03:00:00.000000000',
       '2010-01-01T06:00:00.000000000', '2010-01-01T09:00:00.000000000',
       ...
       '2010-01-08T21:00:00.000000000', '2010-01-09T00:00:00.000000000'], dtype='datetime64[ns]')
Coordinates:
  * time     (time) datetime64[ns] 2010-01-01 2010-01-01T03:00:00 ... 2010-01-09
Attributes:
    long_name:  time
    bounds:     time_bnds

以下几种方法可以获取目标格式的时间字符串:

  • 方法1:使用numpy格式化时间数组
    利用numpy的datetime_as_string函数直接转换,指定纳秒单位保证格式一致:
import numpy as np
time_strings = np.datetime_as_string(time.values, unit='ns')

返回的time_strings是包含所有时间字符串的numpy数组,格式与示例完全匹配。

  • 方法2:直接转换为字符串类型
    通过xarray的astype方法将DataArray转为字符串类型,再提取值:
time_strings = time.astype(str).values

这种方式简洁高效,同样能得到目标格式的字符串数组。

  • 方法3:提取单个时间字符串
    如果只需要某一个特定位置的时间字符串,比如第一个时间点:
# 直接通过索引取值转换
first_time_str = str(time.values[0])
# 或者使用xarray的isel索引
first_time_str = str(time.isel(time=0).values)

以上方法都能生成你需要的YYYY-MM-DDTHH:MM:SS.000000000格式字符串,因为你的时间数据是datetime64[ns]类型且纳秒部分为0,所以输出会保留9位纳秒后缀。

内容的提问来源于stack exchange,提问作者nuvolet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 05:55:09