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

写入YAML文件时如何去除日期值的引号

问题:如何让ruamel.yaml输出无引号的日期格式?

我编写了如下Python脚本:

import json
from datetime import datetime, timedelta
import os
import ruamel.yaml

vulnerabilities = {}
expiration_date = (datetime.now() + timedelta(days=29)).strftime('%Y-%m-%d')
vulnerabilities = [{'expirationDate': expiration_date}]

output_file = 'output_whitelist.yaml'

yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False
with open(output_file, 'w') as file:
    yaml.dump({f'vulnerabilities': vulnerabilities}, file)

当前输出的YAML内容为:

vulnerabilities:
  - expirationDate: '2024-08-16'

但我期望输出无引号的日期格式:

vulnerabilities:
  - expirationDate: 2024-08-16

我尝试使用自定义表示器但未成功:

# Custom representer for datetime.date objects
def date_representer(dumper, data):
    return dumper.scalar(u'tag:yaml.org,2002:str', data)

yaml.add_representer(datetime.date, date_representer)

解决方案

你的自定义表示器未生效的核心原因是:expiration_date是字符串类型,而非datetime.date对象,所以针对datetime.date的表示器不会被触发。以下提供两种可行方案:

方案一:使用datetime.date对象并自定义表示器

将日期字符串转换为datetime.date对象,再为该类型添加表示器,让其输出无引号的日期格式:

import json
from datetime import datetime, timedelta
import os
import ruamel.yaml

# 生成datetime.date对象而非字符串
expiration_date = (datetime.now() + timedelta(days=29)).date()
vulnerabilities = [{'expirationDate': expiration_date}]

output_file = 'output_whitelist.yaml'

yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False

# 自定义date对象的表示器,输出无引号的日期字符串
def date_representer(dumper, data):
    return dumper.represent_scalar('tag:yaml.org,2002:str', data.strftime('%Y-%m-%d'), style='')

yaml.add_representer(datetime.date, date_representer)

with open(output_file, 'w') as file:
    yaml.dump({'vulnerabilities': vulnerabilities}, file)

方案二:直接为字符串类型添加条件表示器

如果需要保留字符串类型,可通过判断字符串格式,仅对YYYY-MM-DD格式的字符串输出无引号:

import json
from datetime import datetime, timedelta
import os
import ruamel.yaml

expiration_date = (datetime.now() + timedelta(days=29)).strftime('%Y-%m-%d')
vulnerabilities = [{'expirationDate': expiration_date}]

output_file = 'output_whitelist.yaml'

yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False

# 自定义字符串表示器,仅对日期格式字符串输出无引号
def str_representer(dumper, data):
    try:
        # 验证是否为YYYY-MM-DD格式
        datetime.strptime(data, '%Y-%m-%d')
        return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='')
    except ValueError:
        # 非日期格式字符串按默认方式处理
        return dumper.represent_scalar('tag:yaml.org,2002:str', data)

yaml.add_representer(str, str_representer)

with open(output_file, 'w') as file:
    yaml.dump({'vulnerabilities': vulnerabilities}, file)

两种方案均可输出你期望的无引号日期格式YAML。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:26:09