Home > front end >  How do I search for a string containing today's date/dates in a file using python?
How do I search for a string containing today's date/dates in a file using python?

Time:09-26

rom pathlib import Path

path = Path('/home/hell/Downloads/hello by Adele/')

search_string = 'completed on "%d/%m/%Y"' #%d/%m/%Y today's date
t=0
for o in path.rglob('*.sql'):
    if o.is_file():
        t= t 1
        text = o.read_text()
        if search_string not in text:
            print(o)
            break

search_string = 'completed on "%d/%m/%Y"'

the script is to search for a string.."completed on 13/13/2022". I would like to add date to the current date to the search parameter but cant figure out how.

kindly assist and thanks

CodePudding user response:

If you use the datetime library, you can get 'today' with

from datetime import date

t = date.today()

This will be a datetime.date object. You can then display it in whatever format you want with the .strftime() method, so you'd have display_date = t.strftime('%d/%m/%Y'). Your new object display_date will be a string in that format.

Do all of that first in your script, and then have your search_string = f'completed on {display_date}'

So in total you will have

from pathlib import Path
from datetime import date

t = date.today()
display_date = t.strftime('%d/%m/%Y')

path = Path('/home/hell/Downloads/hello by Adele/')

search_string = f'completed on {display_date}'
t=0
for o in path.rglob('*.sql'):
    if o.is_file():
        t= t 1
        text = o.read_text()
        if search_string not in text:
            print(o)
            break

CodePudding user response:

first get your today's date to string

from datetime import datetime
dateText = datetime.now().strftime("%d/%m/%Y")

then concat your "search_string"

search_string ='completed on ' dateText 
>>> from datetime import datetime
>>> dateText = datetime.now().strftime("%d/%m/%Y")
>>> search_string ='completed on ' dateText
>>> print(search_string)
completed on 26/09/2022
  • Related