Skip to content

feat: add time_zone to Datetime results #33

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion dataframely/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def __getattr__(self, name: str) -> Any:
try:
import sqlalchemy as sa
import sqlalchemy.dialects.mssql as sa_mssql
import sqlalchemy.dialects.oracle as sa_oracle
import sqlalchemy.dialects.postgresql as sa_postgresql
from sqlalchemy.sql.type_api import TypeEngine as sa_TypeEngine
except ImportError: # pragma: no cover
sa = _DummyModule("sqlalchemy") # type: ignore
Expand All @@ -36,4 +38,4 @@ class sa_TypeEngine: # type: ignore # noqa: N801

# ------------------------------------------------------------------------------------ #

__all__ = ["sa", "sa_mssql", "sa_TypeEngine", "pa"]
__all__ = ["sa", "sa_mssql", "sa_oracle", "sa_postgresql", "sa_TypeEngine", "pa"]
44 changes: 39 additions & 5 deletions dataframely/columns/datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@
import datetime as dt
from collections.abc import Callable
from typing import Any, cast
from zoneinfo import ZoneInfo

import polars as pl

from dataframely._compat import pa, sa, sa_mssql, sa_TypeEngine
from dataframely._compat import (
pa,
sa,
sa_mssql,
sa_oracle,
sa_postgresql,
sa_TypeEngine,
)
from dataframely._polars import (
EPOCH_DATETIME,
date_matches_resolution,
Expand Down Expand Up @@ -265,6 +273,7 @@ def __init__(
max: dt.datetime | None = None,
max_exclusive: dt.datetime | None = None,
resolution: str | None = None,
time_zone: ZoneInfo | str | dt.timezone | None = None,
check: Callable[[pl.Expr], pl.Expr] | None = None,
alias: str | None = None,
metadata: dict[str, Any] | None = None,
Expand All @@ -284,6 +293,7 @@ def __init__(
the formatting language used by :mod:`polars` datetime ``round`` method.
For example, a value ``1h`` expects all datetimes to be full hours. Note
that this setting does *not* affect the storage resolution.
time_zone: The timezone that datetimes in the column must have.
check: A custom check to run for this column. Must return a non-aggregated
boolean expression.
alias: An overwrite for this column's name which allows for using a column
Expand Down Expand Up @@ -317,28 +327,51 @@ def __init__(
metadata=metadata,
)
self.resolution = resolution
self.time_zone = time_zone

@property
def dtype(self) -> pl.DataType:
return pl.Datetime()
return pl.Datetime(time_unit="us", time_zone=self.time_zone)

def validation_rules(self, expr: pl.Expr) -> dict[str, pl.Expr]:
result = super().validation_rules(expr)
if self.resolution is not None:
result["resolution"] = expr.dt.truncate(self.resolution) == expr
if self.time_zone is not None:
time_zone = (
self.time_zone.key
if isinstance(self.time_zone, ZoneInfo)
else self.time_zone
)
result["time_zone"] = pl.coalesce(
expr == pl.selectors.datetime(time_unit="us", time_zone=time_zone),
False,
)
return result

def sqlalchemy_dtype(self, dialect: sa.Dialect) -> sa_TypeEngine:
timezone_enabled = self.time_zone is not None
match dialect.name:
case "mssql":
# sa.DateTime wrongly maps to DATETIME
return sa_mssql.DATETIME2(6)
return sa_mssql.DATETIME2(6, timezone=timezone_enabled)
case "postgresql":
return sa_postgresql.TIMESTAMP(timezone=timezone_enabled)
case "oracle":
return sa_oracle.TIMESTAMP(timezone=timezone_enabled)
case _:
return sa.DateTime()
return sa.DateTime(timezone=timezone_enabled)

@property
def pyarrow_dtype(self) -> pa.DataType:
return pa.timestamp("us")
time_zone = (
self.time_zone.key
if isinstance(self.time_zone, ZoneInfo)
else self.time_zone.tzname(None)
if isinstance(self.time_zone, dt.timezone)
else self.time_zone
)
return pa.timestamp("us", time_zone)

def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series:
return generator.sample_datetime(
Expand All @@ -354,6 +387,7 @@ def _sample_unchecked(self, generator: Generator, n: int) -> pl.Series:
allow_null_response=True,
),
resolution=self.resolution,
time_zone=self.time_zone,
null_probability=self._null_probability,
)

Expand Down
5 changes: 4 additions & 1 deletion dataframely/random.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import datetime as dt
from collections.abc import Sequence
from typing import TypeVar
from zoneinfo import ZoneInfo

import numpy as np
import polars as pl
Expand Down Expand Up @@ -293,6 +294,7 @@ def sample_datetime(
min: dt.datetime,
max: dt.datetime | None,
resolution: str | None = None,
time_zone: ZoneInfo | str | dt.timezone | None = None,
null_probability: float = 0.0,
) -> pl.Series:
"""Sample a list of datetimes in the provided range.
Expand All @@ -303,6 +305,7 @@ def sample_datetime(
max: The maximum datetime to sample (exclusive). '10000-01-01' when ``None``.
resolution: The resolution that datetimes in the column must have. This uses
the formatting language used by :mod:`polars` datetime ``round`` method.
time_zone: The timezone that datetimes in the column must have.
null_probability: The probability of an element being ``null``.
Returns:
Expand All @@ -329,7 +332,7 @@ def sample_datetime(
)
# NOTE: polars tracks datetimes relative to epoch
- _datetime_to_microseconds(EPOCH_DATETIME)
).cast(pl.Datetime)
).cast(pl.Datetime(time_unit="us", time_zone=time_zone))

if resolution is not None:
return result.dt.truncate(resolution)
Expand Down
127 changes: 127 additions & 0 deletions tests/column_types/test_datetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import datetime as dt
from typing import Any
from zoneinfo import ZoneInfo

import polars as pl
import pytest
Expand Down Expand Up @@ -347,16 +348,35 @@ def test_validate_min_max(
@pytest.mark.parametrize(
("column", "values", "valid"),
[
(
dy.Date(),
[dt.date(2020, 1, 1), dt.date(2021, 1, 15), dt.date(2022, 12, 1)],
{},
),
(
dy.Date(resolution="1mo"),
[dt.date(2020, 1, 1), dt.date(2021, 1, 15), dt.date(2022, 12, 1)],
{"resolution": [True, False, True]},
),
(
dy.Time(),
[dt.time(12, 0), dt.time(13, 15), dt.time(14, 0, 5)],
{},
),
(
dy.Time(resolution="1h"),
[dt.time(12, 0), dt.time(13, 15), dt.time(14, 0, 5)],
{"resolution": [True, False, False]},
),
(
dy.Datetime(),
[
dt.datetime(2020, 4, 5),
dt.datetime(2021, 1, 1, 12),
dt.datetime(2022, 7, 10, 0, 0, 1),
],
{},
),
Comment on lines +351 to +379
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I added these since I wanted to double-check the negative case when nothing is specified, but I'm happy to remove them if you believe these are too verbose

(
dy.Datetime(resolution="1d"),
[
Expand Down Expand Up @@ -387,6 +407,113 @@ def test_validate_resolution(
assert_frame_equal(actual, expected)


@pytest.mark.parametrize(
("column", "values", "schema", "valid"),
[
(
dy.Datetime(),
[
dt.datetime(2020, 4, 5, tzinfo=dt.UTC),
dt.datetime(2021, 1, 1, 12, tzinfo=dt.UTC),
dt.datetime(2022, 7, 10, 0, 0, 1, tzinfo=dt.UTC),
],
None,
{},
),
(
dy.Datetime(time_zone="UTC"),
[
dt.datetime(2020, 4, 5),
dt.datetime(2021, 1, 1, 12),
dt.datetime(2022, 7, 10, 0, 0, 1),
],
None,
{"time_zone": [False, False, False]},
),
(
dy.Datetime(time_zone="UTC"),
[
dt.datetime(2020, 4, 5, tzinfo=dt.UTC),
dt.datetime(2021, 1, 1, 12, tzinfo=dt.UTC),
dt.datetime(2022, 7, 10, 0, 0, 1, tzinfo=dt.UTC),
],
None,
{"time_zone": [True, True, True]},
),
(
dy.Datetime(
time_zone=dt.timezone(
dt.timedelta(hours=-7), name="America/Los_Angeles"
)
),
[
dt.datetime(2020, 4, 5),
dt.datetime(2021, 1, 1, 12),
dt.datetime(2022, 7, 10, 0, 0, 1),
],
pl.Datetime(time_zone="America/Los_Angeles"),
{"time_zone": [True, True, True]},
),
(
dy.Datetime(
time_zone=dt.timezone(
dt.timedelta(hours=-7), name="America/Los_Angeles"
)
),
[
dt.datetime(2020, 4, 5),
dt.datetime(2021, 1, 1, 12),
dt.datetime(2022, 7, 10, 0, 0, 1),
],
None,
{"time_zone": [False, False, False]},
),
(
dy.Datetime(time_zone=dt.timezone(dt.timedelta(hours=-7))),
[
dt.datetime(2020, 4, 5),
dt.datetime(2021, 1, 1, 12),
dt.datetime(2022, 7, 10, 0, 0, 1),
],
pl.Datetime(time_zone="America/Los_Angeles"),
{"time_zone": [False, False, False]},
),
(
dy.Datetime(time_zone=ZoneInfo("Etc/UTC")),
[
dt.datetime(2020, 4, 5, tzinfo=ZoneInfo("Etc/UTC")),
dt.datetime(2021, 1, 1, 12, tzinfo=ZoneInfo("Etc/UTC")),
dt.datetime(2022, 7, 10, 0, 0, 1, tzinfo=ZoneInfo("Etc/UTC")),
],
None,
{"time_zone": [True, True, True]},
),
(
dy.Datetime(time_zone=ZoneInfo("Etc/UTC")),
[
dt.datetime(2020, 4, 5, tzinfo=ZoneInfo("America/New_York")),
dt.datetime(2021, 1, 1, 12, tzinfo=ZoneInfo("America/New_York")),
dt.datetime(2022, 7, 10, 0, 0, 1, tzinfo=ZoneInfo("America/New_York")),
],
None,
{"time_zone": [False, False, False]},
),
],
)
def test_validate_datetime_timezone(
column: Column,
values: list[Any],
schema: pl.Datetime | None,
valid: dict[str, list[bool]],
) -> None:
lf = pl.LazyFrame(
{"a": values}, schema={"a": schema} if schema is not None else None
)
actual = evaluate_rules(lf, rules_from_exprs(column.validation_rules(pl.col("a"))))
expected = pl.LazyFrame(valid)
assert_frame_equal(actual, expected)


@pytest.mark.parametrize(
"column",
[
Expand Down
Loading