| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
"""This provides utilities for extracting the local time zone.""" |
| 20 |
|
| 21 |
import time |
| 22 |
from typing import Tuple |
| 23 |
|
| 24 |
|
| 25 |
class TimeZoneFormatMode(object): |
| 26 |
normal = "normal" |
| 27 |
reduced = "reduced" |
| 28 |
extended = "extended" |
| 29 |
|
| 30 |
templates = { |
| 31 |
normal: '{sign}{hh:02d}{mm:02d}', |
| 32 |
reduced: '{sign}{hh:02d}', |
| 33 |
extended: '{sign}{hh:02d}:{mm:02d}' |
| 34 |
} |
| 35 |
|
| 36 |
|
| 37 |
def get_local_time_zone() -> Tuple[int, int]: |
| 38 |
"""Return the current local UTC offset in hours and minutes.""" |
| 39 |
utc_offset_seconds = -time.timezone |
| 40 |
if time.localtime().tm_isdst == 1 and time.daylight: |
| 41 |
utc_offset_seconds = -time.altzone |
| 42 |
sign = -1 if utc_offset_seconds < 0 else 1 |
| 43 |
utc_offset_minutes = (utc_offset_seconds // 60) % (sign * 60) |
| 44 |
utc_offset_hours = sign * ((sign * utc_offset_seconds) // 3600) |
| 45 |
return utc_offset_hours, utc_offset_minutes |
| 46 |
|
| 47 |
|
| 48 |
def get_local_time_zone_format( |
| 49 |
tz_fmt_mode: str = TimeZoneFormatMode.normal |
| 50 |
) -> str: |
| 51 |
"""Return a string denoting the current local UTC offset. |
| 52 |
|
| 53 |
:param tz_fmt_mode: |
| 54 |
:type tz_fmt_mode: TimeZoneFormat: |
| 55 |
""" |
| 56 |
utc_offset_hours, utc_offset_minutes = get_local_time_zone() |
| 57 |
if utc_offset_hours == utc_offset_minutes == 0: |
| 58 |
return "Z" |
| 59 |
if tz_fmt_mode == TimeZoneFormatMode.reduced and utc_offset_minutes != 0: |
| 60 |
tz_fmt_mode = TimeZoneFormatMode.normal |
| 61 |
sign = "-" if (utc_offset_hours < 0 or utc_offset_minutes < 0) else "+" |
| 62 |
timezone_template = TimeZoneFormatMode.templates[tz_fmt_mode] |
| 63 |
return timezone_template.format( |
| 64 |
sign=sign, hh=abs(utc_offset_hours), mm=abs(utc_offset_minutes) |
| 65 |
) |