Search code examples
pythonmongodbpytestpymongo

Python date module for mongodb


Year=2023 month=4 day=28 Userdate = datetime.datetime(year,month, day) For rec in collec.find({“createdat”{“$lte”:datetime.datetime.fromisoformat(userdate)}}): print(rec)

Type error fromisoformat: argument must be str”


Solution

  • MongoDB stores dates as BSON type 9, which stores the number of milliseconds since 1970-01-01 00:00 UTC.

    This means that a year-month-day is not specific enough to be a MongoDB timestamp.

    Instead of {$gte: datetime.date(2023,5,2)}, try {$gte: datetime.datetime(2023,5,2,0,0,0)}

    In the second case you are querying for a string. Since mongodb query operators are type-sensitive, that will never match a date, try:

    collection.find({"create":{"$gte": ISODate("2023-04-27T19:47:00Z")}})