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

如何将从JSONL文件读取的字典列表中的时间戳转换为Datetime格式及报错修复

解决JSONL数据中时间戳转Datetime的TypeError问题

Hey there, let's break down what's causing that error and fix your timestamp conversion task.

问题根源分析

Your error TypeError: string indices must be integers comes from a simple loop mistake:

  • In your nested loop, for value in value_man.keys() is iterating over string key names (like "name", "time_created"), not the dictionary objects themselves.
  • When you try value['time_created'], you're trying to use a string as an index for another string—strings only accept integer indices (e.g., value[0]), which is why the error pops up.

You don't need to loop through every key in each dictionary; you only need to target the specific time_created field directly.

修正后的代码

import jsonlines
import datetime

# 读取JSONL文件到字典列表
with jsonlines.open('data.jsonl', 'r') as jsonl_f:
    lst = [obj for obj in jsonl_f]

# 遍历每个字典,转换时间戳为Datetime格式
for item in lst:
    # 可选:添加判断避免键不存在的情况(增强代码健壮性)
    if 'time_created' in item:
        item['time_created'] = datetime.datetime.fromtimestamp(item['time_created'])

print(lst)

代码说明

  • Removed the unnecessary inner loop: we directly access the time_created key in each dictionary instead of iterating all keys.
  • Added if 'time_created' in item as a safeguard: this prevents errors if any JSON object in the file lacks the time_created field (useful for real-world data that might be inconsistent).
  • The converted datetime object replaces the original timestamp integer, exactly matching your requirement.

When you run this code with your provided JSONL data, each entry's time_created field will become a proper datetime.datetime object (e.g., datetime.datetime(2022, 10, 6, 15, 36, 3) for Thomas's entry).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:54:09