Skip to content
This repository was archived by the owner on Apr 27, 2021. It is now read-only.

Commit ec86839

Browse files
committed
cqle: add the option to truncate datetime values to match DB quantization
PYTHON-273
1 parent 4d691ab commit ec86839

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

cassandra/cqlengine/columns.py

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

1515
from copy import deepcopy, copy
16-
from datetime import date, datetime
16+
from datetime import date, datetime, timedelta
1717
import logging
1818
import six
1919
from uuid import UUID as _UUID
@@ -429,11 +429,27 @@ class DateTime(Column):
429429
"""
430430
db_type = 'timestamp'
431431

432+
truncate_microseconds = False
433+
"""
434+
Set this ``True`` to have model instances truncate the date, quantizing it in the same way it will be in the database.
435+
This allows equality comparison between assigned values and values read back from the database::
436+
437+
DateTime.truncate_microseconds = True
438+
assert Model.create(id=0, d=datetime.utcnow()) == Model.objects(id=0).first()
439+
440+
Defaults to ``False`` to preserve legacy behavior. May change in the future.
441+
"""
442+
432443
def to_python(self, value):
433444
if value is None:
434445
return
435446
if isinstance(value, datetime):
436-
return value
447+
if DateTime.truncate_microseconds:
448+
us = value.microsecond
449+
truncated_us = us // 1000 * 1000
450+
return value - timedelta(microseconds=us - truncated_us)
451+
else:
452+
return value
437453
elif isinstance(value, date):
438454
return datetime(*(value.timetuple()[:6]))
439455

docs/api/cassandra/cqlengine/columns.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@ Columns of all types are initialized by passing :class:`.Column` attributes to t
5454

5555
.. autoclass:: DateTime(**kwargs)
5656

57+
.. autoattribute:: truncate_microseconds
58+
5759
.. autoclass:: Decimal(**kwargs)
5860

5961
.. autoclass:: Double(**kwargs)

0 commit comments

Comments
 (0)