From 9c844fd7f6ead20af27dbbdafb1ecff9fe6e71c9 Mon Sep 17 00:00:00 2001 From: Daniel <d.hornung@indiscale.com> Date: Mon, 6 May 2024 14:24:12 +0200 Subject: [PATCH] ENH: table json converter: timezone handling for datetime --- .../table_json_conversion/fill_xlsx.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/caosadvancedtools/table_json_conversion/fill_xlsx.py b/src/caosadvancedtools/table_json_conversion/fill_xlsx.py index 66495584..46c55ab1 100644 --- a/src/caosadvancedtools/table_json_conversion/fill_xlsx.py +++ b/src/caosadvancedtools/table_json_conversion/fill_xlsx.py @@ -22,6 +22,7 @@ from __future__ import annotations +import datetime import pathlib from types import SimpleNamespace from typing import Any, Optional, TextIO, Union @@ -155,6 +156,7 @@ class TemplateFiller: def _handle_data(self, data: dict, current_path: list[str] = None, context: TemplateFiller.Context = None, only_collect_insertables: bool = False, + utc: bool = False, ) -> Optional[dict[str, Any]]: """Handle the data and write it into ``workbook``. @@ -176,6 +178,8 @@ context: TemplateFiller.Context, optional only_collect_insertables: bool, optional If True, do not insert anything on this level, but return a dict with entries to be inserted. +utc: bool, optional + If True, store times as UTC. Else store as local time on a best-effort base. Returns ------- @@ -233,6 +237,13 @@ out: union[dict, None] value = content[0] if isinstance(value, str): value = ILLEGAL_CHARACTERS_RE.sub("", value) + if isinstance(value, datetime.datetime): + if value.tzinfo is not None: + if utc: + value = value.astimezone(datetime.timezone.utc).replace(tzinfo=None) + else: + # Remove timezone, store in local timezone. + value = value.astimezone().replace(tzinfo=None) path_str = p2s(path) assert path_str not in insertables -- GitLab