[英]How to convert a string date in mongodb to ISODate(), or DATE() and delete if it is less than 30 days using python?
Using python I saved dates into MongoDB in below format, 我使用python将日期以以下格式保存到MongoDB中,
completed_time : "2017:08:20 02:30:02"
Now I want to delete all entries which are older than 30 days. 现在,我要删除所有超过30天的条目。 How can I implement that logic?
如何实现该逻辑?
You can use the datetime
module to convert your date/time string into a datetime
object, and then convert it to an ordinal day (just a single number), and compare it to the day that was thirty days ago. 您可以使用
datetime
模块将日期/时间字符串转换为datetime
对象,然后将其转换为有序日期(仅一个数字),然后将其与30天之前的日期进行比较。
Hopefully this will do what you want: 希望这会做您想要的:
import datetime
completed_time = "2017:07:20 02:30:02"
timeFormat = '%Y:%m:%d %H:%M:%S'
thisDate = datetime.datetime.strptime(completed_time, timeFormat).toordinal()
today = datetime.date.today()
thirtyDaysAgo = today.toordinal() - 30
if thisDate < thirtyDaysAgo:
print("That needs deleting!")
You can do it more simply. 您可以更简单地进行操作。 This code is considerably longer than needed, in order to be explanatory.
为了便于说明,此代码比所需的代码长得多。
I first create a collection of MongoDB records with dates that start from about a month and a half ago, and end about two two weeks ago. 我首先创建一个MongoDB记录集合,其日期从大约一个半月前开始,到大约两个两周前结束。
>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> db = client.test_database
>>> from datetime import datetime, timedelta
>>> some_dates = [datetime(2017, 7, d).strftime('%Y:%m:%d %H:%M:%S') for d in range(15,31)]+[datetime(2017, 8, d).strftime('%Y:%m:%d %H:%M:%S') for d in range(1,16)]
>>> posts = db.create_collection
>>> for some_date in some_dates:
... post = {'completed_time': some_date, 'stuff': 'more stuff'}
... post_id = posts.insert_one(post).inserted_id
...
This calculates the time and date that is (or was) 30 days earlier than 'now' when I calculated it, and puts it in the format in you MongoDB database. 计算的时间和日期比我计算时的“现在”早(或早)30天,并将其以您的MongoDB数据库格式显示。
>>> boundary = (datetime.now()-timedelta(30)).strftime('%Y:%m:%d %H:%M:%S')
This counts the number of records in the database whose dates and times precede the value in boundary
just calculated, for later reference. 这将对数据库中记录的日期和时间在刚计算的
boundary
值之前的记录数进行计数,以供以后参考。
>>> count = 0
>>> for post in posts.find({'completed_time': {'$lt': boundary}}):
... count+=1
...
>>> count
19
This is the one line that, with the calculation of boundary
, does what you want. 这是一条线,与计算
boundary
,你想要做什么。
>>> r = posts.delete_many({'completed_time': {'$lt': boundary}})
Now we can check that the correct number of records has been deleted. 现在我们可以检查是否已删除正确数量的记录。
>>> count = 0
>>> for post in posts.find({'completed_time': {'$lt': boundary}}):
... count+=1
...
>>> count
0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.