简体   繁体   English

从 python 的列表中检索数据时进行查询

[英]queries while retrieving data from list in python

I have a list in python which has below data.我在 python 中有一个列表,其中包含以下数据。 each data represent a table name每个数据代表一个表名

[tablename_20211011, tablename_20201010, tablename_20211009, tablename_20211009, tablename_20211008] [tablename_20211011,tablename_20201010,tablename_20211009,tablename_20211009,tablename_20211008]

20211011 -- this is the date when table got created how i can fetch the table names which are created in last 1 year python. 20211011 - 这是创建表的日期,我如何获取在过去 1 年 python 中创建的表名。

if crteria is 1 yr then result should be tablename_20211011,tablename_20211009, tablename_20211008,tablename_20211009如果 crteria 为 1 年,则结果应为 tablename_20211011,tablename_20211009, tablename_20211008,tablename_20211009

!!!works!!! !!!作品!!! here you dont need to mention last year date manually it does the job automatically在这里你不需要手动提及去年的日期它会自动完成这项工作

from datetime import date
(datetime.datetime.now() - datetime.timedelta(days=365)).strftime("%Y%m%d")
d1 = today.strftime("%Y%m%d")
#this gives you date of last year

[x for x in a if x[:-8]>=d1]

this returns the items after the given date这将返回给定日期之后的项目

Assuming that it is always the last 8 characters of your filename that are the date (ie. YYYYMMDD format), you could just use:假设您的文件名的最后 8 个字符始终是日期(即YYYYMMDD格式),您可以只使用:

files = ['tablename_20211011', 'tablename_20201010', 'tablename_20211009', 'tablename_20211009', 'tablename_20211008']

print ([x for x in files if x[-8:] >= '20210101'])

Simply set the date-string to the right of the >= symbol as needed.只需根据需要将日期字符串设置在>=符号的右侧。

If the date is not always the last 8 characters of the string, then you may need to use a regular expression (regex) approach to extract it.如果日期并不总是字符串的最后 8 个字符,那么您可能需要使用正则表达式 (regex) 方法来提取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM