"""Time helpers. * Camera local * System local * UTC Timestamp to datetime * Timestamp * in UTC * Timezone * Implicit system local timezone * No known timezone * Known timezone Datetime to timestamp * always store as local time * optionally with UTC offset Part of the tagit module. A copy of the license is provided with the project. Author: Matthias Baumgartner, 2022 """ # standard imports from datetime import timezone, datetime, tzinfo, timedelta # exports __all__ = ('timestamp', 'from_timestamp') ## code ## timestamp_loc = lambda dt: dt.replace(tzinfo=timezone.utc).timestamp() timestamp_utc = lambda dt: dt.timestamp() from_timestamp_loc = lambda ts: datetime.utcfromtimestamp(ts) from_timestamp_utc = lambda ts: datetime.fromtimestamp(ts) now = datetime.now timestamp_min = timestamp_loc(datetime.min) timestamp_max = timestamp_loc(datetime.max) def utcoffset(dt): if dt.tzinfo is None: return local_tzo(dt) elif dt.tzinfo is NoTimeZone: return None else: return dt.tzinfo.utcoffset(dt).total_seconds() / 3600 NoTimeZone = timezone(timedelta(0), 'NoTimeZone') def local_tzo(dt=None): """Return the offset between the local time and UTC. (i.e. return the x of UTC+x). """ dt = datetime.now() if dt is None else dt return (timestamp_loc(dt) - dt.timestamp()) / 3600 ## EOF ##