如何用Python提取XML注释时间并转换为Epoch时间戳?
从XML注释提取时间并转换为Epoch时间戳
以下是用Python实现的完整解决方案,分三步完成需求:
1. 提取XML中的注释节点
Python标准库xml.etree.ElementTree支持访问XML的注释节点,代码如下:
import xml.etree.ElementTree as ET import re from datetime import datetime # 读取XML文件(也可直接传入XML字符串) tree = ET.parse("your_xml_file.xml") root = tree.getroot() # 遍历节点提取注释内容 comment_text = "" for node in root.iter(): if isinstance(node, ET.Comment): comment_text = node.text.strip() break # 假设仅需第一个目标注释,找到后停止遍历
2. 从注释中匹配时间字符串
用正则表达式匹配注释里的DD MON YYYY HH:MM:SS AM/PM格式时间:
# 正则匹配时间模式 time_pattern = r"\b(\d{2} [A-Z]{3} \d{4} \d{1,2}:\d{2}:\d{2} [AP]M)\b" match = re.search(time_pattern, comment_text) if not match: raise ValueError("注释中未找到目标时间格式") time_str = match.group(1)
3. 转换为Epoch时间戳
用datetime.strptime解析时间字符串,再转换为秒级Epoch时间戳:
# 定义时间格式:%d=日,%b=缩写月份,%Y=年,%I=12小时制小时,%M=分钟,%S=秒,%p=AM/PM time_format = "%d %b %Y %I:%M:%S %p" dt = datetime.strptime(time_str, time_format) # 转换为Epoch时间戳 epoch_timestamp = dt.timestamp() print(f"Epoch时间戳:{epoch_timestamp}")
完整可运行代码
import xml.etree.ElementTree as ET import re from datetime import datetime def extract_epoch_from_xml_comment(xml_path): # 解析XML tree = ET.parse(xml_path) root = tree.getroot() # 提取目标注释 comment_text = "" for node in root.iter(): if isinstance(node, ET.Comment) and "Generated" in node.text: comment_text = node.text.strip() break if not comment_text: raise ValueError("XML中未找到含时间的注释节点") # 匹配时间字符串 time_pattern = r"\b(\d{2} [A-Z]{3} \d{4} \d{1,2}:\d{2}:\d{2} [AP]M)\b" match = re.search(time_pattern, comment_text) if not match: raise ValueError("注释中未找到符合格式的时间") # 解析并转换为Epoch时间戳 time_str = match.group(1) time_format = "%d %b %Y %I:%M:%S %p" dt = datetime.strptime(time_str, time_format) return dt.timestamp() # 使用示例 if __name__ == "__main__": try: timestamp = extract_epoch_from_xml_comment("movies.xml") print(f"转换后的Epoch时间戳:{timestamp}") except Exception as e: print(f"错误:{e}")
注意事项
- 若XML存在多个注释,可通过关键词(如示例中的"Generated")精准筛选目标注释
- 时间格式中的空格需和注释里的完全匹配(示例中时间前后为两个空格),若你的XML空格数量不同,需调整正则和格式字符串
- 如需毫秒级时间戳,可将结果乘以1000:
epoch_timestamp * 1000
内容的提问来源于stack exchange,提问作者Nelly Yuki
相关产品推荐
相关产品推荐

