Skip to content Skip to sidebar Skip to footer

Select Based On Timestamp And Update Timestamp With Zero

How do I select records from a date field which has a time (HH:MM:SS.Milisecond) value greater than zero from a MongoDB collection and update it with a time (HH:MM:SS) value as zer

Solution 1:

ISODate() is represented as a datetime object by PyMongo. MongoDB assumes that dates and times are in UTC. There are several ways to get midnight (start of a day) for a given UTC time d:

>>>from datetime import datetime, time, timedelta>>>d = datetime(2015, 10, 13, 1, 4, 30, 515000)>>>datetime(d.year, d.month, d.day) # @user3100115' answer
datetime.datetime(2015, 10, 13, 0, 0)   # 369 ns
>>>datetime.fromordinal(d.toordinal()) # 451 ns
datetime.datetime(2015, 10, 13, 0, 0)
>>>datetime.combine(d, time.min)       # 609 ns
datetime.datetime(2015, 10, 13, 0, 0)
>>>d - (d - d.min) % timedelta(days=1) # Python 3
datetime.datetime(2015, 10, 13, 0, 0)   # 1.87 µs
>>>datetime(*d.timetuple()[:3])
datetime.datetime(2015, 10, 13, 0, 0)   # 2.34 µs
>>>from calendar import timegm>>>datetime.utcfromtimestamp((timegm(d.timetuple()) // 86400) * 86400) # POSIX
datetime.datetime(2015, 10, 13, 0, 0)   # 4.72 µs

Solution 2:

The best way to update your documents and set the time to 00:00:00 is using the datetime module, because createdDate is a datetime object in Python, so you can use the datetime instance attributes day, year, and month.

from datetime import datetime

from pymongo importMongoClientclient= MongoClient()
db = client.testcollection= db.collectionbulkOp= collection.initialize_ordered_bulk_op()
count = 0for doc in collection.find():
    year = doc['createdDate'].yearmonth= doc['createdDate'].monthday= doc['createdDate'].daynew_date= datetime(year, month, day)
    bulkOp.find({'_id': doc['_id']}).update({'$set': {'createdDate': new_date}})
    count = count + 1ifcount== 125:
        bulkOp.execute()
        bulkOp = collection.initialize_ordered_bulk_op()

if count % 125 != 0:
   bulkOp.execute()

Post a Comment for "Select Based On Timestamp And Update Timestamp With Zero"