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

如何将obspy的UTCDateTime时间数据存储到HDF5数据库

问题原因
  • 转换逻辑错误:你先对字符串执行encode()得到bytes类型,又用str()包裹bytes对象,得到的是带b'前缀的字符串(如"b'2015-03-26T16:02:42.000000Z'"),不是原始时间字符串。
  • 存储dtype参数错误:h5py的dtype='str'会映射到HDF5不原生支持的变长Unicode类型dtype('<U'),不存在默认转换路径,因此抛出类型错误。
  • 额外的低级错误:你做转换时循环的输入变量是未定义的time_str,正确的输入应该是原始时间列表times。
可行存储方案

方案1:存储POSIX时间戳(推荐)

该方案占用空间最小,后续数值计算、时间筛选无需额外格式转换,性能最优。

存储代码

import h5py
import numpy as np
from obspy.core.utcdatetime import UTCDateTime

# 直接提取UTCDateTime的时间戳属性,精度保留到微秒
timestamps = [t.timestamp for t in times]

with h5py.File('data_ML.hdf5', 'w') as f:
    f.create_dataset(
        "time", 
        data=np.array(timestamps, dtype=np.float64),
        maxshape=(None,), 
        chunks=True
    )

读取转换代码

with h5py.File('data_ML.hdf5', 'r') as f:
    stored_timestamps = f['time'][:]
# 直接转回UTCDateTime格式
restore_times = [UTCDateTime(ts) for ts in stored_timestamps]

方案2:存储固定长度ASCII字节串

如果你需要直接在HDF5文件中查看可读的时间字符串,可以使用该方案。

存储代码

import h5py
import numpy as np

# 转换为标准ISO格式的ASCII字节串
time_bytes = [str(t).encode('ascii') for t in times]
# 指定dtype为S27,适配你使用的27位带Z的ISO时间格式长度
time_arr = np.array(time_bytes, dtype='S27')

with h5py.File('data_ML.hdf5', 'w') as f:
    f.create_dataset(
        "time", 
        data=time_arr,
        maxshape=(None,), 
        chunks=True
    )

读取转换代码

with h5py.File('data_ML.hdf5', 'r') as f:
    stored_bytes = f['time'][:]
# 转回字符串
restore_str = [b.decode('ascii') for b in stored_bytes]
# 直接转回UTCDateTime也可,obspy支持bytes格式的时间输入
restore_times = [UTCDateTime(b) for b in stored_bytes]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 19:39:04