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

将calendar.xml中的时间戳转换为dd-mm-yyyy格式求实现代码

解决方案:将XML中的时间戳转换为dd-mm-yyyy格式

直接用Python脚本就能完成这个需求,无需额外依赖,步骤如下:

代码实现

import xml.etree.ElementTree as ET
from datetime import datetime, timezone

# 读取XML文件
tree = ET.parse('calendar.xml')
root = tree.getroot()

# 遍历所有日历条目
for entry in root.findall('calendar_entry'):
    # 处理start_date
    start_date_elem = entry.find('start_date')
    if start_date_elem is not None and start_date_elem.text.strip():
        try:
            timestamp = int(start_date_elem.text.strip())
            # 转换为UTC日期,格式化为dd-mm-yyyy
            date = datetime.fromtimestamp(timestamp, timezone.utc).strftime('%d-%m-%Y')
            start_date_elem.text = date
        except ValueError:
            # 若时间戳无效,保留原内容
            pass
    
    # 处理end_date
    end_date_elem = entry.find('end_date')
    if end_date_elem is not None and end_date_elem.text.strip():
        try:
            timestamp = int(end_date_elem.text.strip())
            date = datetime.fromtimestamp(timestamp, timezone.utc).strftime('%d-%m-%Y')
            end_date_elem.text = date
        except ValueError:
            pass

# 保存转换后的XML文件(避免覆盖原文件)
tree.write('calendar_converted.xml', encoding='UTF-8', xml_declaration=True)
print("转换完成,已保存为calendar_converted.xml")

使用说明

  • 将上述代码保存为convert_timestamps.py,和你的calendar.xml放在同一文件夹
  • 打开命令行进入该文件夹,运行命令:python convert_timestamps.py
  • 转换后的文件会以calendar_converted.xml为名生成,原文件不会被修改

代码说明

  • 用Python内置的xml.etree.ElementTree解析XML,无需安装额外库
  • 遍历每个calendar_entry节点,提取start_date和end_date的时间戳
  • 将秒级时间戳转换为UTC日期,再格式化为dd-mm-yyyy格式
  • 加入异常处理,遇到无效时间戳时保留原内容,避免脚本崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:57:42