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

如何将表示Timestamp列表的字符串转为Python中的Timestamp列表?

把Timestamp列表字符串转成Python Timestamp列表的方法

假设你这里的Timestamp是pandas里的时间戳类型,下面给两种靠谱的实现方式:

方法1:用ast模块安全解析(推荐)

ast.literal_eval比直接用eval安全,不会执行恶意代码。我们可以结合ast.NodeTransformer来把字符串里的Timestamp节点转换成pandas的Timestamp对象:

import ast
import pandas as pd

class TimestampTransformer(ast.NodeTransformer):
    def visit_Call(self, node):
        # 识别调用Timestamp的节点
        if isinstance(node.func, ast.Name) and node.func.id == 'Timestamp':
            # 提取时间字符串参数
            time_str = node.args[0].s
            # 返回一个常量节点,值为pd.Timestamp对象
            return ast.Constant(value=pd.Timestamp(time_str))
        return self.generic_visit(node)

# 你的输入字符串
input_str = "[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), Timestamp('2022-08-13 18:46:00')]"

# 解析并转换
tree = ast.parse(input_str, mode='eval')
transformer = TimestampTransformer()
transformed_tree = transformer.visit(tree)
timestamp_list = ast.literal_eval(transformed_tree)

print(timestamp_list)
print(type(timestamp_list[0]))  # 输出 <class 'pandas._libs.tslibs.timestamps.Timestamp'>

方法2:字符串拆分提取(简单直接)

如果输入格式固定,也可以直接拆分字符串提取时间,再逐个转换:

import pandas as pd

input_str = "[Timestamp('2022-08-13 17:25:00'), Timestamp('2022-08-13 18:02:00'), Timestamp('2022-08-13 18:46:00')]"

# 去掉首尾的[],然后拆分每个Timestamp项
items = input_str.strip('[]').split(', Timestamp(')
# 处理第一项,去掉开头的Timestamp('
items[0] = items[0].replace("Timestamp('", "")
# 遍历所有项,提取时间字符串并转换
timestamp_list = [pd.Timestamp(item.strip("'")) for item in items]

print(timestamp_list)

注意:如果你的Timestamp是其他库的类型,只需要把pd.Timestamp换成对应的类即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:10:37