Date
Date fields store datetime values. Times are always stored in UTC, though with appropriate support packages installed (pytz and/or tzlocal) this can include timezone support.
Import
from marrow.mongo.field import Date
Inherits
marrow.mongo:Field
Available
>=1.1.2
Attributes
This field type inherits all Field attributes and represents a singular, scalar date/time value.
naive
naiveTimezone to interpret naive `datetime` objects as utilizing.
Defaultutc
Added>=1.1.3
tz
tzTimezone to cast to when retrieving from the database.
Default()
Added>=1.1.3
Timezone references as utilized by the above may be any of:
The constant string
"naive", resulting in no timezone transformation or alteration of thetzinfoattribute at all.The constant string
"local", auto-detecting the host's timezone, requiring the packagelocaltzbe installed. This is most useful if you usedatetime.now()instead ofdatetime.utcnow()—please consider updating your code to utilize the UTC variant in preference to this.A
tzinfoobject, such as those provided by thepytzpackage.
Any use of timezone awareness will require the pytz package be installed, as Python's built-in tzinfo objects suffer a number of issues. Note also that use of timezones comes with a performance penalty.
Usage
Instantiate and assign an instance of this class during construction of a new Document subclass. Accessing as a class attribute will return a Queryable allowing filtering operations, and access as an instance attribute will return a datetime cast value.
Date fields are highly aware of date-like objects and how to apply them. For example, you may provide any of the following in place of a pure datetime value:
Any
MutableMappinginstance (such as adictorDocumentinstance) with an_idkey whose value is anObjectId. The date/time value will be pulled automatically from the_id.generation_time.A bare BSON
ObjectIdinstance, behaving as above.A
datetime.timedeltainstance whose value will be immediately applied (added to) the result ofdatetime.utcnow().A
datetimeinstance.
Examples
Typecasting Behaviour and Querying
A key reason for the above typecasting allowances are to permit natural comparison against those types of objects as admittedly, it'll be unlikely you'll need to populate a date from the ID of a record.
Given a Date field named modified, you can identify all documents modified in the last 30 days easily and without performing date math yourself: (remembering that the value being queried for becomes static after that comparison)
query = Asset.modified >= timedelta(days=-30)
Asset.find(query)Last updated
Was this helpful?