I have this script:
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)
The output shows this:
vulnerabilities:
- expirationDate: '2024-08-16'
but I would like to show it like this:
vulnerabilities:
- expirationDate: 2024-08-16
without the quotes. Is this possible?
I tried using a custom representer, but that didn’t work:
# 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)
1
Your initial approach didn’t work because the custom representer was designed for datetime.date
objects but was applied to strings, leading to dates being treated and quoted as plain strings in the YAML.
This should work:
from datetime import datetime, timedelta
import os
import ruamel.yaml
def str_representer(dumper, data):
try:
datetime.strptime(data, '%Y-%m-%d')
return dumper.represent_scalar('tag:yaml.org,2002:timestamp', data)
except ValueError:
return dumper.represent_scalar('tag:yaml.org,2002:str', data)
yaml = ruamel.yaml.YAML()
yaml.default_flow_style = False
yaml.representer.add_representer(str, str_representer)
vulnerabilities = {}
expiration_date = (datetime.now() + timedelta(days=29)).strftime('%Y-%m-%d')
vulnerabilities = [{'expirationDate': expiration_date}]
script_dir = os.path.dirname(os.path.abspath(__file__))
output_file = os.path.join(script_dir, 'output_whitelist.yaml')
with open(output_file, 'w') as file:
yaml.dump({'vulnerabilities': vulnerabilities}, file)
d.mainardi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
0
The output that you want is the standard output for datetime.date
objects. You get the quotes because you make the value for expirationDate
into a string, and that string cannot be dumped without quotes, as it would be read back as a date.
There are several other superfluous lines in your code (imports and vulnerabilities = {}
). Simplified code to get the output you want:
from datetime import date as Date, timedelta as TimeDelta
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
expiration_date = Date.today() + TimeDelta(days=29)
vulnerabilities = [{'expirationDate': expiration_date}]
yaml.dump(dict(vulnerabilities=vulnerabilities), sys.stdout)
which gives:
vulnerabilities:
- expirationDate: 2024-08-16
Or if you really need to calculate using datetime.datetime
instances, use the .date()
method to get a datetime.date
from a datetime.datetime
and don’t use .strftime()