如何将从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_createdkey in each dictionary instead of iterating all keys. - Added
if 'time_created' in itemas a safeguard: this prevents errors if any JSON object in the file lacks thetime_createdfield (useful for real-world data that might be inconsistent). - The converted
datetimeobject 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
相关产品推荐
相关产品推荐

