diff --git a/pygeoapi/util.py b/pygeoapi/util.py index 30a18de57..8c051b44a 100644 --- a/pygeoapi/util.py +++ b/pygeoapi/util.py @@ -202,13 +202,29 @@ def path_representer(dumper, data): yaml.add_multi_representer(pathlib.PurePath, path_representer) + def datetime_representer(dumper, data: datetime): + if data.tzinfo is None: + data = data.replace(tzinfo=timezone.utc) + else: + data = data.astimezone(timezone.utc) + value = data.strftime("%Y-%m-%dT%H:%M:%SZ") + + # timestamp in a specified format, without string quotes + return dumper.represent_scalar(u'tag:yaml.org,2002:timestamp', value) + + # create a dedicated dumper to write datetime to yaml correctly + class MyDumper(yaml.SafeDumper): + pass + + MyDumper.add_representer(datetime, datetime_representer) + lock = FileLock(f'{destfile}.lock') with lock: LOGGER.debug('Dumping YAML document') with open(destfile, 'wb') as fh: yaml.dump(dict_, fh, sort_keys=False, encoding='utf8', indent=4, - default_flow_style=False) + default_flow_style=False, allow_unicode=True, Dumper=MyDumper) return True