mongoengine icon indicating copy to clipboard operation
mongoengine copied to clipboard

DatetimeField - how to accept values like "new Date()" or "new ISODate()"

Open ronhanson opened this issue 9 years ago • 2 comments

Hi, I would like to set a datetime value to, let's say, now, with now being the mongo's server current datetime. Fact is that if we use python :

obj.my_datetime_field = datetime.utcnow()

The datetime will be calculate on the client site, at the time the value is set and pushed to the server.

But if I want the datetime to be server's time (often machines have shifted times) as a reference. The way we can do that in mongo shell is to use Javascript code like this :

{ "my_datetime_field" = new Date(), ... }

In that case, the value will be calculated as the now of the mongo's server.

This case can also be useful for a delayed call to the save() method on the object. A field can be set to the date it was saved but not the date the field was first set in python.

The way I can cope with that at the moment, is to use a DynamicField and do like this :

obj.my_datetime_field = bson.code.Code("new Date()")

That would be great to be able to use a Code object as well as a valid value for a DatetimeField.

Does that make sense to you? Would you accept a pull request about that ?

While here, thanks much for the awesome work. Mongoengine really rocks.

ronhanson avatar Jul 05 '17 21:07 ronhanson

Well actually, in this example I wrote earlier :

obj.my_datetime_field = bson.code.Code("new Date()")

This does not behave as expected as the value is not calculated but stored as a JS callable in the database, so date is always recalculated when queried :

> db.mycol.find()
{ "_id" : ObjectId("595d5d2e91fdcd02cc7d5fb1"), "created" : ISODate("2017-07-05T21:45:10.488**Z") }
> db.mycol.find() # one minute + secs later
{ "_id" : ObjectId("595d5d2e91fdcd02cc7d5fb1"), "created" : ISODate("2017-07-05T21:46:15.051Z") }

See the date that changes... So it is always the now date and always gets recalculated...

But if I insert a document like this :

db.mycol.insert({"created" = new Date()})

It works fine and the date stays the right insert moment.

Any idea on how we could achieve the same with mongoengine ?

ronhanson avatar Jul 05 '17 21:07 ronhanson

@ronhanson I am using

from datetime import datetime
class User(Document):
     created_at = DateTimeField(default=datetime.utcnow)

daxlab avatar Sep 17 '17 17:09 daxlab