Skip to content

Commit

Permalink
feat(python): Validate time_zone in Datetime class
Browse files Browse the repository at this point in the history
  • Loading branch information
luke396 committed May 11, 2024
1 parent 21b3d43 commit 1e28cae
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions py-polars/polars/datatypes/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,11 +458,8 @@ def __init__(
)
raise ValueError(msg)

if isinstance(time_zone, timezone):
time_zone = str(time_zone)

self.time_unit = time_unit
self.time_zone = time_zone
self.time_zone = self._validate_timezone(time_zone)

def __eq__(self, other: PolarsDataType) -> bool: # type: ignore[override]
# allow comparing object instances to class
Expand All @@ -484,6 +481,26 @@ def __repr__(self) -> str:
f"{class_name}(time_unit={self.time_unit!r}, time_zone={self.time_zone!r})"
)

def _validate_timezone(self, time_zone: str | timezone | None) -> str | None:
if time_zone is None or time_zone == "*" or isinstance(time_zone, timezone):
time_zone = time_zone
else:
from polars._utils.convert import (
string_to_zoneinfo,
)
from polars.dependencies import _ZONEINFO_AVAILABLE, zoneinfo

if _ZONEINFO_AVAILABLE:
try:
time_zone = string_to_zoneinfo(time_zone)
except (zoneinfo.ZoneInfoNotFoundError, TypeError):
msg = f"invalid time zone: {time_zone!r}, to see valid strings run `import zoneinfo; zoneinfo.available_timezones()`"
raise ValueError(msg) from None
else:
msg = "install polars[timezone] to handle datetimes with time zone information"
raise ImportError(msg)
return str(time_zone)


class Duration(TemporalType):
"""
Expand Down

0 comments on commit 1e28cae

Please sign in to comment.