Skip to content

Commit

Permalink
Merge pull request #423 from LuckySting/fix/datetime-aware
Browse files Browse the repository at this point in the history
Fix datetime timezoine aware usage
  • Loading branch information
rekby authored May 2, 2024
2 parents 3735a42 + 5161f9e commit 213405c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
6 changes: 4 additions & 2 deletions tests/aio/test_types.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import ydb

from datetime import date, datetime, timedelta
from datetime import date, datetime, timedelta, timezone
from decimal import Decimal
from uuid import uuid4

Expand Down Expand Up @@ -51,8 +51,9 @@ async def test_types(driver, database, value, ydb_type):

test_td = timedelta(microseconds=-100)
test_now = datetime.utcnow()
test_today = date.today()
test_today = test_now.date()
test_dt_today = datetime.today()
tz4h = timezone(timedelta(hours=4))


@pytest.mark.parametrize(
Expand All @@ -63,6 +64,7 @@ async def test_types(driver, database, value, ydb_type):
(test_today, "Date", test_today),
(365, "Date", date(1971, 1, 1)),
(3600 * 24 * 365, "Datetime", datetime(1971, 1, 1, 0, 0)),
(datetime(1970, 1, 1, 4, 0, tzinfo=tz4h), "Timestamp", datetime(1970, 1, 1, 0, 0)),
(test_td, "Interval", test_td),
(test_now, "Timestamp", test_now),
(
Expand Down
9 changes: 7 additions & 2 deletions ydb/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import enum
import json
from . import _utilities, _apis
from datetime import date, datetime, timedelta
from datetime import date, datetime, timedelta, timezone
import typing
import uuid
import struct
Expand All @@ -23,6 +23,7 @@

_SECONDS_IN_DAY = 60 * 60 * 24
_EPOCH = datetime(1970, 1, 1)
_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=timezone.utc)


def _from_date(x: ydb_value_pb2.Value, table_client_settings: table.TableClientSettings) -> typing.Union[date, int]:
Expand Down Expand Up @@ -90,7 +91,11 @@ def _from_timestamp(

def _to_timestamp(pb: ydb_value_pb2.Value, value: typing.Union[datetime, int]):
if isinstance(value, datetime):
pb.uint64_value = _timedelta_to_microseconds(value - _EPOCH)
if value.tzinfo:
epoch = _EPOCH_UTC
else:
epoch = _EPOCH
pb.uint64_value = _timedelta_to_microseconds(value - epoch)
else:
pb.uint64_value = value

Expand Down

0 comments on commit 213405c

Please sign in to comment.