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

将NumPy数组中的字符串转换为%Y格式的日期(保留数组类型)

解决方案

要将NumPy字符串数组中的日期转换为%Y格式(四位数年份)的数组,同时保持NumPy类型,可以按以下步骤操作:

方法1:生成%Y格式的字符串数组

import numpy as np

ray = ['01.01.88', '01.01.99', '01.01.87', '01.01.89', '01.01.96',
       '01.01.95', '01.01.95']
ray = np.array(ray)

# 直接解析数组为datetime64类型,无需转回列表
parsed_dates = np.strptime(ray, '%d.%m.%y')
# 格式化为仅含四位数年份的字符串数组
year_str_array = np.datetime_as_string(parsed_dates, unit='Y')

print(year_str_array)
# 输出:array(['1988', '1999', '1987', '1989', '1996', '1995', '1995'], dtype='<U4')

方法2:保留datetime64年份类型

如果需要数组仍为日期类型(而非纯字符串),可转换为datetime64[Y]类型:

year_datetime_array = parsed_dates.astype('datetime64[Y]')

print(year_datetime_array)
# 输出:array(['1988', '1999', '1987', '1989', '1996', '1995', '1995'], dtype='datetime64[Y]')

关键说明

  • np.strptime原生支持NumPy数组输入,完全不需要将ray转回列表。
  • %d.%m.%y是匹配原字符串的格式符:%d对应日、%m对应月、%y对应两位年份,NumPy会自动将两位年份映射为1970-2069区间的四位数年份(如88→1988、99→1999)。
  • np.datetime_as_string可将datetime64数组按指定单位格式化,unit='Y'表示仅保留年份部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:39:19