queries while retrieving data from list in python

Viewed 51

I have a list in python which has below data . each data represent a table name

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

if crteria is 1 yr then result should be tablename_20211011,tablename_20211009, tablename_20211008,tablename_20211009

2 Answers

!!!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:

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.

Related