Debian Codegraph @

metomi/isodatetime/timezone.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # ----------------------------------------------------------------------------
3 # Copyright (C) British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
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 )