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

Python中无法将所有时间戳项添加到列表的问题求助

问题描述

我有一个时间戳列表timestamp_list,需要将其中的时间戳格式化后添加至新列表。目前已实现单个时间戳的格式化,但仅能往新列表中添加一项——尽管原列表允许存在重复项,且原时间戳仅毫秒部分存在差异(该情况并非固定)。

给出的时间戳列表:

timestamp_list = ['2023-03-15T08:14:54.920Z', '2023-03-15T08:14:54.921Z', '2023-03-15T08:14:54.919Z', 
                  '2023-03-15T08:14:54.918Z', '2023-03-15T08:14:54.918Z', '2023-03-15T08:14:54.916Z', 
                  '2023-03-15T08:14:54.916Z', '2023-03-15T08:14:54.916Z', '2023-03-15T08:14:54.921Z', '2023-03-15T08:14:54.920Z']

我的代码:

formatted_timestamp_list = []
def format_time():
    for timestamp in timestamp_list:
        #Convert datetime to string
        pattern = '%Y-%m-%dT%H:%M:%S.%fZ'
        dt = datetime.strptime(timestamp, pattern)
        new_timestamp = str(dt + timedelta(hours=1))[:-3] + 'Z'
        #Format timestamp to a more readable pattern
        formatted_time = (''.join(letter for letter in new_timestamp if not letter.isalpha()))[:19]
        formatted_time2 = formatted_time[:10] + ' /' + formatted_time[10:]
        formatted_timestamp_list.append(formatted_time2)
        return formatted_timestamp_list
new_formatted_time_list = format_time()
print(new_formatted_time_list)

当前输出:

['2023-03-15 / 09:14:54']

期望输出:

['2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54','2023-03-15 / 09:14:54']
修复方案

问题核心在于return formatted_timestamp_list的位置错误——它被放在了for循环内部,导致循环第一次迭代就直接返回列表,后续时间戳完全没机会处理。

将return语句移到for循环外部即可解决,同时优化了时间格式化逻辑,用strftime直接生成目标格式,比字符串过滤拼接更简洁可靠:

from datetime import datetime, timedelta

timestamp_list = ['2023-03-15T08:14:54.920Z', '2023-03-15T08:14:54.921Z', '2023-03-15T08:14:54.919Z', 
                  '2023-03-15T08:14:54.918Z', '2023-03-15T08:14:54.918Z', '2023-03-15T08:14:54.916Z', 
                  '2023-03-15T08:14:54.916Z', '2023-03-15T08:14:54.916Z', '2023-03-15T08:14:54.921Z', '2023-03-15T08:14:54.920Z']

formatted_timestamp_list = []
def format_time():
    for timestamp in timestamp_list:
        # 转换时间戳为datetime对象并加1小时
        pattern = '%Y-%m-%dT%H:%M:%S.%fZ'
        dt = datetime.strptime(timestamp, pattern)
        dt_plus_1h = dt + timedelta(hours=1)
        # 直接生成目标格式的字符串
        formatted_time = dt_plus_1h.strftime('%Y-%m-%d / %H:%M:%S')
        formatted_timestamp_list.append(formatted_time)
    # 循环结束后统一返回列表
    return formatted_timestamp_list

new_formatted_time_list = format_time()
print(new_formatted_time_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:57:26