codekingpro/portable-devtools
114k
1"""2Timezone utility functions.3"""4 5# Copyright (C) 2020 The Psycopg Team6 7import logging8from typing import Dict, Optional, Union9from datetime import timezone, tzinfo10 11from .pq.abc import PGconn12from ._compat import ZoneInfo13 14logger = logging.getLogger("psycopg")15 16_timezones: Dict[Union[None, bytes], tzinfo] = {17 None: timezone.utc,18 b"UTC": timezone.utc,19}20 21 22def get_tzinfo(pgconn: Optional[PGconn]) -> tzinfo:23 """Return the Python timezone info of the connection's timezone."""24 tzname = pgconn.parameter_status(b"TimeZone") if pgconn else None25 try:26 return _timezones[tzname]27 except KeyError:28 sname = tzname.decode() if tzname else "UTC"29 try:30 zi: tzinfo = ZoneInfo(sname)31 except (KeyError, OSError):32 logger.warning("unknown PostgreSQL timezone: %r; will use UTC", sname)33 zi = timezone.utc34 except Exception as ex:35 logger.warning(36 "error handling PostgreSQL timezone: %r; will use UTC (%s - %s)",37 sname,38 type(ex).__name__,39 ex,40 )41 zi = timezone.utc42 43 _timezones[tzname] = zi44 return zi45 