tzutil.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. from datetime import datetime
  3. from typing import Tuple
  4. import pytz
  5. tzlocal = None
  6. try:
  7. import tzlocal # Maybe we can use the tzlocal module to get a safe timezone
  8. except ImportError:
  9. pass
  10. # Set the local timezone for DateTime conversions. Note in most cases we want to use either UTC or the server
  11. # timezone, but if someone insists on using the local timezone we will try to convert. The problem is we
  12. # never have anything but an epoch timestamp returned from ClickHouse, so attempts to convert times when the
  13. # local timezone is "DST" aware (like 'CEST' vs 'CET') will be wrong approximately half the time
  14. local_tz: pytz.timezone
  15. local_tz_dst_safe: bool = False
  16. def normalize_timezone(timezone: pytz.timezone) -> Tuple[pytz.timezone, bool]:
  17. if timezone.tzname(None) in ('UTC', 'GMT', 'Universal', 'GMT-0', 'Zulu', 'Greenwich'):
  18. return pytz.UTC, True
  19. if timezone.tzname(None) in pytz.common_timezones:
  20. return timezone, True
  21. if tzlocal is not None: # Maybe we can use the tzlocal module to get a safe timezone
  22. local_name = tzlocal.get_localzone_name()
  23. if local_name in pytz.common_timezones:
  24. return pytz.timezone(local_name), True
  25. return timezone, False
  26. try:
  27. local_tz = pytz.timezone(os.environ.get('TZ', ''))
  28. except pytz.UnknownTimeZoneError:
  29. local_tz = datetime.now().astimezone().tzinfo
  30. local_tz, local_tz_dst_safe = normalize_timezone(local_tz)