Home > Software engineering >  How to insert specific date format for Date in mongoDB with pymongo?
How to insert specific date format for Date in mongoDB with pymongo?

Time:10-25

I simply need one of my collections to have a TTL index.

The documentation states that i should do something like this :

db.log_events.insert( { "expireAt": new Date('July 22, 2013 14:00:00'), "logEvent": 2, "logMessage": "Success!" } )

With an index on expireAt field.
I have as input a int that represents the time since epoch in milliseconds and I need to create the above date.

How can I build such date with datetime and pymongo from a millisSinceEpoch integer?

I have found many answers but I have no idea if the TTL index will work with any date format different than the one shown above (from the documentation).

CodePudding user response:

Convert your timestamp using datetime.datetime.fromtimestamp(), bearing in mind this takes an input in seconds. You may need to divide by 1,000 to get milliseconds.

https://docs.python.org/3/library/datetime.html#datetime.date.fromtimestamp

Sample code, converts to and from POSIX timestamp:

import pymongo
import datetime

client = pymongo.MongoClient()
db = client['mydatabase']

dt = datetime.datetime.utcnow()

ts = dt.timestamp()
print(ts)

db.mycollection.insert_one({'date': datetime.datetime.fromtimestamp(ts)})

print(list(db.mycollection.find({'date': dt}, {'_id': 0})))

prints:

1635066038.917683
[{'date': datetime.datetime(2021, 10, 24, 10, 0, 38, 917000)}]
  • Related