如何将MS Access的Date/Time Extended字节串转换为可读格式?
解决MS Access Date/Time Extended字段的字节对象转换问题
针对你遇到的Access Date/Time Extended字段返回字节对象的问题,核心是这个字节流本质是带分隔符的数字字符串编码,而非二进制结构,所以不能直接用struct解析,正确的处理步骤如下:
转换逻辑说明
Access的Date/Time Extended类型存储为三个用冒号分隔的部分:
- 第一部分:从基准日期
1899-12-30开始的天数偏移量 - 第二部分:以100纳秒为单位的时间偏移量
- 第三部分:精度标识(比如
7代表100纳秒精度)
我们需要先将字节解码为字符串,拆分各部分后计算出对应的datetime对象。
代码实现
from datetime import datetime, timedelta def parse_access_datetime_extended(byte_data): # 解码字节为字符串,去除末尾的空终止符 raw_str = byte_data.decode('utf-8').rstrip('\x00') # 拆分日期偏移、时间偏移、精度字段 days_str, hundred_nanos_str, _ = raw_str.split(':') # 转换为整数 days_offset = int(days_str) hundred_nanos = int(hundred_nanos_str) # Access Date/Time的基准日期 base_date = datetime(1899, 12, 30) # 计算日期部分 date_component = base_date + timedelta(days=days_offset) # 计算时间部分:100纳秒 = 0.1微秒,转微秒后构造timedelta time_component = timedelta(microseconds=hundred_nanos // 10) # 合并日期和时间 return date_component + time_component
使用示例
针对你提供的字节对象:
sample_byte = b'0000000000000693593:0000000576000000000:7\x00' converted_dt = parse_access_datetime_extended(sample_byte) # 输出指定格式的字符串 print(converted_dt.strftime('%I:%M:%S.%f %p')) # 结果:04:00:00.000000 PM
如果需要保留7位小数的纳秒精度,可以手动拼接字符串:
# 提取7位纳秒(100纳秒单位的最后一位) nanos_7th = hundred_nanos % 10 formatted_str = f"{converted_dt.strftime('%I:%M:%S.%f')}{nanos_7th} {converted_dt.strftime('%p')}" print(formatted_str) # 结果:04:00:00.0000000 PM
注意事项
- 若解码时出现编码错误,可尝试替换编码为
cp1252(Access旧版本常用编码) - 基准日期
1899-12-30是Access Date/Time类型的标准起始点,与Excel的1900日期系统兼容(忽略Excel的闰年bug)
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

