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

如何递归检查并替换Python嵌套字典中的datetime值为Unix时间戳

递归转换嵌套字典中的datetime为Unix时间戳

我有一个包含多层嵌套键和嵌套字典的复杂Python字典,其中部分值是datetime格式,需要将这些datetime值转换为Unix时间戳(转换逻辑已明确)。

示例输入

from datetime import datetime

input_data = {
    "maybetime": datetime(),
    "other": 12,
    "other2": "xxx",
    "nested": {
        "maybetime": datetime(),
        "other": 12,
        "other2": "xxx",
        "other3": datetime()
    }
}

期望输出

{
    "maybetime": 13213213213,
    "other": 12,
    "other2": "xxx",
    "nested": {
        "maybetime": 3213213213,
        "other": 12,
        "other2": "xxx",
        "other3": 3213213213
    }
}

解决方案

可以写一个递归函数遍历字典的所有元素,按需转换datetime对象:

from datetime import datetime

def datetime_to_timestamp(data):
    # 如果是字典,递归处理每个键值对
    if isinstance(data, dict):
        return {key: datetime_to_timestamp(value) for key, value in data.items()}
    # 如果是datetime对象,转换为Unix时间戳(示例为毫秒级,可根据需求调整)
    elif isinstance(data, datetime):
        return int(data.timestamp() * 1000)
    # 其他类型直接返回原数据
    else:
        return data

函数说明

  • 递归遍历输入数据:遇到字典就深入处理内部的每个键值对,支持任意层级的嵌套
  • 精准识别datetime对象:通过类型判断锁定需要转换的元素,执行自定义转换逻辑(示例中转为毫秒级时间戳,若需秒级可去掉*1000)
  • 非目标类型元素保持原样:数字、字符串等其他类型不会被修改,保证数据结构完整性

使用示例

# 构造测试数据
test_data = {
    "maybetime": datetime(2023, 10, 1),
    "other": 12,
    "other2": "xxx",
    "nested": {
        "maybetime": datetime(2023, 10, 2),
        "other": 12,
        "other2": "xxx",
        "other3": datetime(2023, 10, 3)
    }
}

# 执行转换
result = datetime_to_timestamp(test_data)
print(result)

运行后,所有datetime对象都会被转换为对应的Unix时间戳,嵌套字典也会被正确处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:42:20