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

如何将字典中的时间戳键值对转换为datetime格式并计算与当前时间差值

错误原因

datetime.strptime() 是用于解析字符串格式时间的方法,你传入字典类型参数自然会触发类型不匹配报错。

正确实现方案

你存储的字典已经包含了datetime构造所需的全部时间字段,直接提取对应字段构造datetime对象即可,无需转字符串再解析。

方法1:手动提取字段构造(可读性最高)

import datetime

timestamp_info = {
    'day': 8, 'fold': 0, 'hour': 0,
    'max': {'day': 31, 'fold': 0,'hour': 23},
    'microsecond': 639000, 'minute': 17, 'month': 10, 'second': 35, 'year': 2021
}

# 构造datetime对象
target_dt = datetime.datetime(
    year=timestamp_info['year'],
    month=timestamp_info['month'],
    day=timestamp_info['day'],
    hour=timestamp_info['hour'],
    minute=timestamp_info['minute'],
    second=timestamp_info['second'],
    microsecond=timestamp_info['microsecond'],
    fold=timestamp_info['fold']
)

# 计算和当前时间的秒级差值
# 注意:如果存储的是UTC时间,请使用datetime.datetime.utcnow()对比避免时区误差
current_dt = datetime.datetime.now()
diff_seconds = (current_dt - target_dt).total_seconds()
# 如需整数秒可直接转int
int_diff_seconds = int(diff_seconds)

方法2:自动过滤字段+字典解包(适合字段多的场景)

先过滤掉字典中多余的max无效键,再直接解包字典传入构造函数:

valid_fields = {'year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond', 'fold'}
filtered_params = {k:v for k,v in timestamp_info.items() if k in valid_fields}
target_dt = datetime.datetime(**filtered_params)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 16:09:01