Skip to content

Commit

Permalink
Refactor to use pytz instead of pendulum (#527)
Browse files Browse the repository at this point in the history
* Refactor to use pytz instead of pendulum

* Fix math in `get_timezone`

* Troubleshoot offset calculation in `get_timezone`
Add second timezone test case to account for runner location

---------

Co-authored-by: Daniel McKnight <daniel@neon.ai>
  • Loading branch information
NeonDaniel and NeonDaniel authored May 31, 2024
1 parent d40f920 commit 4dba8e5
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 4 deletions.
9 changes: 6 additions & 3 deletions neon_utils/location_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,13 @@
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from time import time

import pendulum
import pytz

from datetime import datetime
from typing import Optional, Union

from dateutil.tz import tzlocal
from timezonefinder import TimezoneFinder
from re import sub
Expand Down Expand Up @@ -143,10 +145,11 @@ def get_timezone(lat, lng) -> (str, float):
Note that some coordinates do not have a city, but may have a county.
:param lat: latitude
:param lng: longitude
:return: timezone name, offset from GMT
:return: timezone name, offset in hours from UTC
"""
timezone = TimezoneFinder().timezone_at(lng=float(lng), lat=float(lat))
offset = pendulum.from_timestamp(0, timezone).offset_hours
offset = pytz.timezone(timezone).utcoffset(
datetime.now()).total_seconds() / 3600
return timezone, offset


Expand Down
2 changes: 1 addition & 1 deletion requirements/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
ovos-bus-client~=0.0.3
combo-lock~=0.2
pendulum~=2.1
pytz>=2022.1
timezonefinder~=5.2
nltk~=3.5
pyyaml>=5.4,<7.0
Expand Down
6 changes: 6 additions & 0 deletions tests/location_util_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ def test_get_timezone_from_coords(self):
self.assertIsInstance(offset, float)
self.assertIn(offset, (-7.0, -8.0))

lat = 35.0000
lon = 103.000
timezone, offset = get_timezone(lat, lon)
self.assertEqual(timezone, "Asia/Shanghai")
self.assertEqual(offset, 8.0)

def test_to_system_time(self):
from neon_utils.location_utils import to_system_time
tz_aware_dt = datetime.now(gettz("America/NewYork"))
Expand Down

0 comments on commit 4dba8e5

Please sign in to comment.