From c67a99fb5d3ed3b771f769f5c40e947453e66dda Mon Sep 17 00:00:00 2001 From: Dion Moult Date: Fri, 22 Jan 2021 16:21:17 +1100 Subject: [PATCH] New IfcOpenShell date utility module, because we shouldn't need to think too hard about dates --- .../ifcopenshell/util/date.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/ifcopenshell-python/ifcopenshell/util/date.py diff --git a/src/ifcopenshell-python/ifcopenshell/util/date.py b/src/ifcopenshell-python/ifcopenshell/util/date.py new file mode 100644 index 0000000000..e1bca4089b --- /dev/null +++ b/src/ifcopenshell-python/ifcopenshell/util/date.py @@ -0,0 +1,45 @@ +from re import findall +from datetime import datetime + + +def duration2dict(duration): + results = {} + for number, unit in findall("(?P\d+)(?PS|M|H|D|W|Y)", duration): + results[unit] = number + return results + + +def ifc2datetime(element): + if isinstance(element, str) and element[0] == "P": # IfcDuration + return duration2dict(element) + elif isinstance(element, str): # IfcDateTime, IfcDate + return datetime.fromisoformat(element) + elif isinstance(element, int): # IfcTimeStamp + return datetime.fromtimestamp(element) + elif element.is_a("IfcDateAndTime"): + return datetime( + element.DateComponent.YearComponent, + element.DateComponent.MonthComponent, + element.DateComponent.DayComponent, + element.TimeComponent.HourComponent, + element.TimeComponent.MinuteComponent, + element.TimeComponent.SecondComponent, + # TODO: implement TimeComponent timezone + ) + elif element.is_a("IfcCalendarDate"): + return datetime( + element.YearComponent, + element.MonthComponent, + element.DayComponent, + ) + + +def datetime2ifc(dt, ifc_type): + if ifc_type == "IfcTimeStamp": + return int(dt.timestamp()) + elif ifc_type == "IfcDateTime": + return dt.isoformat() + elif ifc_type == "IfcDate": + return dt.date().isoformat() + elif ifc_type == "IfcTime": + return dt.time().isoformat()