选择基于时间戳并用z更新时间戳

2024-10-03 23:22:16 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从具有时间(HH:MM:毫秒)从MongoDB集合中获取大于零的值,并使用时间(HH:MM:SS)值更新它,方法是使日期值与Python脚本中的现有值保持相同?

当前数据如下-

1) "createdDate" : ISODate("2015-10-10T00:00:00Z")
2) "createdDate" : ISODate("2015-10-11T00:00:00Z")
3) "createdDate" : ISODate("2015-10-12T00:00:00Z")
4) "createdDate" : ISODate("2015-10-13T01:04:30.515Z")
5) "createdDate" : ISODate("2015-10-14T02:05:50.516Z")
6) "createdDate" : ISODate("2015-10-15T03:06:60.517Z")
7) "createdDate" : ISODate("2015-10-16T04:07:80.518Z")

如何使用mongodbsql只选择第4、5、6和7行,并在Python脚本中将时间戳更新为零?

更新后,数据如下所示-

^{pr2}$

Tags: 数据方法脚本mongodbhh时间ss中将
2条回答

更新文档和^{}时间的最佳方法是使用datetime模块,因为createdDate是Python中的datetime object,因此可以使用datetime实例属性^{}^{}和{a6}。在

from datetime import datetime

from pymongo import MongoClient

client = MongoClient()
db = client.test
collection = db.collection
bulkOp = collection.initialize_ordered_bulk_op()
count = 0
for doc in collection.find():
    year = doc['createdDate'].year
    month = doc['createdDate'].month
    day = doc['createdDate'].day
    new_date = datetime(year, month, day)
    bulkOp.find({'_id': doc['_id']}).update({'$set': {'createdDate': new_date}})
    count = count + 1
    if count == 125:
        bulkOp.execute()
        bulkOp = collection.initialize_ordered_bulk_op()

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

PyMongo将ISODate()表示为datetime对象。MongoDB假设日期和时间是UTC格式。对于给定的UTC时间,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

相关问题 更多 >