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

如何用.split()从NetCDF时间格式1970-1-1T00:00:00Z提取两位时/分/秒

提取NetCDF时间字段中的时、分、秒

你的问题出在代码中仅截取了时间字符串的单个字符,导致只能拿到一位数字。要正确提取时分秒,可以按以下步骤处理:

先从units中拆分出完整的时间字符串,再通过split()逐步分离出时分秒部分:

# 从units中提取完整时间字符串,示例:从"hours since 1970-1-1T00:00:00Z"中取出"1970-1-1T00:00:00Z"
time_str = nc['time'].units.split(' ')[2]
# 拆分出时间段并去掉末尾的Z,得到"00:00:00"
time_part = time_str.split('T')[1].rstrip('Z')
# 按冒号拆分时分秒
hour_str, minute_str, second_str = time_part.split(':')

# 按需转换为整数类型
hour = int(hour_str)
minute = int(minute_str)
second = int(second_str)

print(hour_str)  # 输出 '00'
print(hour)      # 输出 0

如果需要保留两位格式的小时字符串,直接使用hour_str即可;如果需要数值形式,转成整数后显示为0是正常的数值表示,若要格式化输出两位格式可以用f"{hour:02d}"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:02:52