-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathtimezone_adjuster.py
31 lines (25 loc) · 1.04 KB
/
timezone_adjuster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# Copyright 2016-2023 Florian Pigorsch & Contributors. All rights reserved.
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file.
import datetime
import typing
import pytz
import s2sphere # type: ignore
import timezonefinder # type: ignore
class TimezoneAdjuster:
_timezonefinder: typing.Optional[timezonefinder.TimezoneFinder] = None
def __init__(self) -> None:
if not TimezoneAdjuster._timezonefinder:
TimezoneAdjuster._timezonefinder = timezonefinder.TimezoneFinder()
@classmethod
def adjust(cls, time: datetime.datetime, latlng: s2sphere.LatLng) -> datetime.datetime:
# If a timezone is set, there's nothing to do.
if time.utcoffset():
return time
assert cls._timezonefinder
# if tz_name name is None set it to UTC
tz_name = cls._timezonefinder.timezone_at(lat=latlng.lat().degrees, lng=latlng.lng().degrees) or "UTC"
tz = pytz.timezone(tz_name)
tz_time = time.astimezone(tz)
return tz_time