如何将表示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
相关产品推荐
相关产品推荐

