简体   繁体   English

如何将mongodb中的字符串日期转换为ISODate()或DATE(),如果使用Python少于30天,如何将其删除?

[英]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.

相关问题 如何使用Python PyMongo将MongoDB日期字符串转换并覆盖到ISODate中? - How to convert and over write MongoDB date string into ISODate using Python PyMongo? 在 PySpark 中将 isodate 字符串转换为日期格式 - Convert an isodate string into date format in PySpark 在MongoDB中将字符串转换为ISODate - Convert string to ISODate in MongoDB 如何使用python日期格式字符串和strptime函数将天数转换为小时数? - How to convert number of days to hours using python date format string and strptime function? 如何从python中的日期和Tkinter中的相同日期打印前30天 - how to print previous 30 days from a date in python and the same in Tkinter 在Python中将MongoDB日期格式转换为String(不使用dateToString) - Convert MongoDB Date format to String in Python (without using dateToString) Python检查日期是否是未来30天 - Python check that the date is 30 days in the future 如何在Python中转换日期时间并计算天数? - How to convert time of the date and count the days in python? 如何使用 Python 将日期字符串转换为 Solr 日期格式? - How to convert date string to Solr date format using Python? 在Python中如何将字符串转换为日期并检查其是否早于5分钟 - In Python how to convert a string to a date and check if it is earlier than 5 mins
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM