Skip to content

Commit caaee9f

Browse files
committed
Replace datetime.utcfromtimestamp
It is depricated and to be removed soon. datetime.fromtimestamp either include timezone into datetime, which we do not want, or offset datetime from utc. So, in order to have same behavior we have to ship separate function that provides same results as datetime.utcfromtimestamp
1 parent d62eb38 commit caaee9f

File tree

7 files changed

+35
-22
lines changed

7 files changed

+35
-22
lines changed

cassandra/cqlengine/columns.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,15 +13,15 @@
1313
# limitations under the License.
1414

1515
from copy import deepcopy, copy
16-
from datetime import date, datetime, timedelta
16+
from datetime import date, datetime, timedelta, timezone
1717
import logging
1818
from uuid import UUID as _UUID
1919

2020
from cassandra import util
2121
from cassandra.cqltypes import SimpleDateType, _cqltypes, UserType
2222
from cassandra.cqlengine import ValidationError
2323
from cassandra.cqlengine.functions import get_total_seconds
24-
from cassandra.util import Duration as _Duration
24+
from cassandra.util import Duration as _Duration, utcfromtimestamp
2525

2626
log = logging.getLogger(__name__)
2727

@@ -551,7 +551,7 @@ def to_python(self, value):
551551
elif isinstance(value, date):
552552
return datetime(*(value.timetuple()[:6]))
553553

554-
return datetime.utcfromtimestamp(value)
554+
return utcfromtimestamp(value)
555555

556556
def to_database(self, value):
557557
value = super(DateTime, self).to_database(value)

cassandra/query.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
import warnings
2727

2828
from cassandra import ConsistencyLevel, OperationTimedOut
29-
from cassandra.util import unix_time_from_uuid1, maybe_add_timeout_to_query
29+
from cassandra.util import unix_time_from_uuid1, maybe_add_timeout_to_query, utcfromtimestamp
3030
from cassandra.encoder import Encoder
3131
import cassandra.encoder
3232
from cassandra.policies import ColDesc
@@ -1100,7 +1100,7 @@ class TraceEvent(object):
11001100

11011101
def __init__(self, description, timeuuid, source, source_elapsed, thread_name):
11021102
self.description = description
1103-
self.datetime = datetime.fromtimestamp(unix_time_from_uuid1(timeuuid), tz=timezone.utc)
1103+
self.datetime = utcfromtimestamp(unix_time_from_uuid1(timeuuid))
11041104
self.source = source
11051105
if source_elapsed is not None:
11061106
self.source_elapsed = timedelta(microseconds=source_elapsed)

cassandra/util.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,17 @@
4040

4141
from cassandra import DriverException
4242

43+
44+
def utcfromtimestamp(timestamp):
45+
"""
46+
It replicates behavior of datetime.utcfromtimestamp
47+
"""
48+
dt = datetime.datetime.fromtimestamp(timestamp, datetime.timezone.utc)
49+
return datetime.datetime(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, fold=dt.fold)
50+
51+
4352
DATETIME_EPOC = datetime.datetime(1970, 1, 1)
44-
UTC_DATETIME_EPOC = datetime.datetime.utcfromtimestamp(0)
53+
UTC_DATETIME_EPOC = utcfromtimestamp(0)
4554

4655
_nan = float('nan')
4756

tests/integration/cqlengine/columns/test_validation.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import unittest
1616

1717
import sys
18-
from datetime import datetime, timedelta, date, tzinfo, time
18+
from datetime import datetime, timedelta, date, tzinfo, time, timezone
1919
from decimal import Decimal as D
2020
from uuid import uuid4, uuid1
2121
from packaging.version import Version
@@ -30,6 +30,7 @@
3030
from cassandra.cqlengine.models import Model, ValidationError
3131
from cassandra.cqlengine.usertype import UserType
3232
from cassandra import util
33+
from cassandra.util import utcfromtimestamp
3334

3435
from tests.integration import PROTOCOL_VERSION, CASSANDRA_VERSION, greaterthanorequalcass30, greaterthanorequalcass3_11
3536
from tests.integration.cqlengine.base import BaseCassEngTestCase
@@ -97,7 +98,7 @@ def test_datetime_timestamp(self):
9798
dt_value = 1454520554
9899
self.DatetimeTest.objects.create(test_id=5, created_at=dt_value)
99100
dt2 = self.DatetimeTest.objects(test_id=5).first()
100-
self.assertEqual(dt2.created_at, datetime.utcfromtimestamp(dt_value))
101+
self.assertEqual(dt2.created_at, utcfromtimestamp(dt_value))
101102

102103
def test_datetime_large(self):
103104
dt_value = datetime(2038, 12, 31, 10, 10, 10, 123000)
@@ -809,7 +810,7 @@ def test_conversion_specific_date(self):
809810
assert isinstance(uuid, UUID)
810811

811812
ts = (uuid.time - 0x01b21dd213814000) / 1e7 # back to a timestamp
812-
new_dt = datetime.utcfromtimestamp(ts)
813+
new_dt = utcfromtimestamp(ts)
813814

814815
# checks that we created a UUID1 with the proper timestamp
815816
assert new_dt == dt

tests/integration/cqlengine/model/test_model_io.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515

1616
from uuid import uuid4, UUID
1717
import random
18-
from datetime import datetime, date, time
18+
from datetime import datetime, date, time, timezone
1919
from decimal import Decimal
2020
from operator import itemgetter
2121

@@ -26,7 +26,7 @@
2626
from cassandra.cqlengine.management import drop_table
2727
from cassandra.cqlengine.models import Model
2828
from cassandra.query import SimpleStatement
29-
from cassandra.util import Date, Time, Duration
29+
from cassandra.util import Date, Time, Duration, utcfromtimestamp
3030
from cassandra.cqlengine.statements import SelectStatement, DeleteStatement, WhereClause
3131
from cassandra.cqlengine.operators import EqualsOperator
3232

@@ -200,13 +200,13 @@ class AllDatatypesModel(Model):
200200

201201
sync_table(AllDatatypesModel)
202202

203-
input = ['ascii', 2 ** 63 - 1, bytearray(b'hello world'), True, datetime.utcfromtimestamp(872835240),
203+
input = ['ascii', 2 ** 63 - 1, bytearray(b'hello world'), True, utcfromtimestamp(872835240),
204204
Decimal('12.3E+7'), 2.39, 3.4028234663852886e+38, '123.123.123.123', 2147483647, 'text',
205205
UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'), UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'),
206206
int(str(2147483647) + '000')]
207207

208208
AllDatatypesModel.create(id=0, a='ascii', b=2 ** 63 - 1, c=bytearray(b'hello world'), d=True,
209-
e=datetime.utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39,
209+
e=utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39,
210210
h=3.4028234663852886e+38, i='123.123.123.123', j=2147483647, k='text',
211211
l=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'),
212212
m=UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), n=int(str(2147483647) + '000'),

tests/integration/cqlengine/model/test_udts.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414
import unittest
1515

16-
from datetime import datetime, date, time
16+
from datetime import datetime, date, time, timezone
1717
from decimal import Decimal
1818
from mock import Mock
1919
from uuid import UUID, uuid4
@@ -23,7 +23,7 @@
2323
from cassandra.cqlengine import columns, connection
2424
from cassandra.cqlengine.management import sync_table, drop_table, sync_type, create_keyspace_simple, drop_keyspace
2525
from cassandra.cqlengine import ValidationError
26-
from cassandra.util import Date, Time
26+
from cassandra.util import Date, Time, utcfromtimestamp
2727

2828
from tests.integration import PROTOCOL_VERSION
2929
from tests.integration.cqlengine.base import BaseCassEngTestCase
@@ -272,7 +272,7 @@ def test_can_insert_udts_with_all_datatypes(self):
272272
self.addCleanup(drop_table, AllDatatypesModel)
273273

274274
input = AllDatatypes(a='ascii', b=2 ** 63 - 1, c=bytearray(b'hello world'), d=True,
275-
e=datetime.utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39,
275+
e=utcfromtimestamp(872835240), f=Decimal('12.3E+7'), g=2.39,
276276
h=3.4028234663852886e+38, i='123.123.123.123', j=2147483647, k='text',
277277
l=UUID('FE2B4360-28C6-11E2-81C1-0800200C9A66'),
278278
m=UUID('067e6162-3b6f-4ae2-a171-2470b63dff00'), n=int(str(2147483647) + '000'))

tests/unit/test_types.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@
1717
import tempfile
1818
import time
1919
from binascii import unhexlify
20+
from datetime import tzinfo
21+
22+
from dateutil.tz import tzlocal
2023

2124
import cassandra
2225
from cassandra import util
@@ -41,7 +44,7 @@
4144
from cassandra.util import (
4245
OPEN_BOUND, Date, DateRange, DateRangeBound,
4346
DateRangePrecision, Time, ms_timestamp_from_datetime,
44-
datetime_from_timestamp
47+
datetime_from_timestamp, utcfromtimestamp
4548
)
4649
from tests.unit.util import check_sequence_consistency
4750

@@ -200,7 +203,7 @@ def test_empty_value(self):
200203

201204
def test_datetype(self):
202205
now_time_seconds = time.time()
203-
now_datetime = datetime.datetime.utcfromtimestamp(now_time_seconds)
206+
now_datetime = utcfromtimestamp(now_time_seconds)
204207

205208
# Cassandra timestamps in millis
206209
now_timestamp = now_time_seconds * 1e3
@@ -211,7 +214,7 @@ def test_datetype(self):
211214
# deserialize
212215
# epoc
213216
expected = 0
214-
self.assertEqual(DateType.deserialize(int64_pack(1000 * expected), 0), datetime.datetime.utcfromtimestamp(expected))
217+
self.assertEqual(DateType.deserialize(int64_pack(1000 * expected), 0), utcfromtimestamp(expected))
215218

216219
# beyond 32b
217220
expected = 2 ** 33
@@ -738,7 +741,7 @@ def get_upper_bound(seconds):
738741
The way to do this is to add one month and leave the date at YEAR-MONTH-01 00:00:00 000000.
739742
Then substract one millisecond.
740743
"""
741-
dt = datetime.datetime.fromtimestamp(seconds / 1000.0, tz=utc_timezone)
744+
dt = utcfromtimestamp(seconds / 1000.0)
742745
dt = dt + datetime.timedelta(days=32)
743746
dt = dt.replace(day=1) - datetime.timedelta(microseconds=1)
744747
return int((dt - self.epoch).total_seconds() * 1000)
@@ -765,7 +768,7 @@ def get_upper_bound(seconds):
765768
The way to do this is to add one year and leave the date at YEAR-01-01 00:00:00 000000.
766769
Then substract one millisecond.
767770
"""
768-
dt = datetime.datetime.fromtimestamp(seconds / 1000.0, tz=utc_timezone)
771+
dt = utcfromtimestamp(seconds / 1000.0)
769772
dt = dt + datetime.timedelta(days=370)
770773
dt = dt.replace(day=1) - datetime.timedelta(microseconds=1)
771774

@@ -812,7 +815,7 @@ def truncate_date(number):
812815
For example if truncate_kwargs = {"hour": 0, "minute": 0, "second": 0, "microsecond": 0} the returned
813816
value will be the original given date but with the hours, minutes, seconds and microseconds set to 0
814817
"""
815-
dt = datetime.datetime.fromtimestamp(number / 1000.0, tz=utc_timezone)
818+
dt = utcfromtimestamp(number / 1000.0)
816819
dt = dt.replace(**truncate_kwargs)
817820
return round((dt - self.epoch).total_seconds() * 1000.0)
818821

0 commit comments

Comments
 (0)