Skip to content

Commit 213405c

Browse files
authored
Merge pull request #423 from LuckySting/fix/datetime-aware
Fix datetime timezoine aware usage
2 parents 3735a42 + 5161f9e commit 213405c

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

tests/aio/test_types.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import pytest
22
import ydb
33

4-
from datetime import date, datetime, timedelta
4+
from datetime import date, datetime, timedelta, timezone
55
from decimal import Decimal
66
from uuid import uuid4
77

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

5252
test_td = timedelta(microseconds=-100)
5353
test_now = datetime.utcnow()
54-
test_today = date.today()
54+
test_today = test_now.date()
5555
test_dt_today = datetime.today()
56+
tz4h = timezone(timedelta(hours=4))
5657

5758

5859
@pytest.mark.parametrize(
@@ -63,6 +64,7 @@ async def test_types(driver, database, value, ydb_type):
6364
(test_today, "Date", test_today),
6465
(365, "Date", date(1971, 1, 1)),
6566
(3600 * 24 * 365, "Datetime", datetime(1971, 1, 1, 0, 0)),
67+
(datetime(1970, 1, 1, 4, 0, tzinfo=tz4h), "Timestamp", datetime(1970, 1, 1, 0, 0)),
6668
(test_td, "Interval", test_td),
6769
(test_now, "Timestamp", test_now),
6870
(

ydb/types.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
import enum
66
import json
77
from . import _utilities, _apis
8-
from datetime import date, datetime, timedelta
8+
from datetime import date, datetime, timedelta, timezone
99
import typing
1010
import uuid
1111
import struct
@@ -23,6 +23,7 @@
2323

2424
_SECONDS_IN_DAY = 60 * 60 * 24
2525
_EPOCH = datetime(1970, 1, 1)
26+
_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=timezone.utc)
2627

2728

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

9192
def _to_timestamp(pb: ydb_value_pb2.Value, value: typing.Union[datetime, int]):
9293
if isinstance(value, datetime):
93-
pb.uint64_value = _timedelta_to_microseconds(value - _EPOCH)
94+
if value.tzinfo:
95+
epoch = _EPOCH_UTC
96+
else:
97+
epoch = _EPOCH
98+
pb.uint64_value = _timedelta_to_microseconds(value - epoch)
9499
else:
95100
pb.uint64_value = value
96101

0 commit comments

Comments
 (0)