I want to add startDate, last seven days of the current date, and end date as today date automatically in API in python can anyone help me?
response = requests.get('http://172.24.105.27:8092/Co=LT&StartDate=06-05-2022&EndDate=14-05-2022', headers=my_headers)
s = response.json()
CodePudding user response:
Can you try the following:
import datetime
today = datetime.datetime.today()
start = (today - datetime.timedelta(days=7)).strftime('%d-%m-%Y')
end = today.strftime('%d-%m-%Y')
response = requests.get(f'http://172.24.105.27:8092/Co=LT&StartDate={start}&EndDate={end}', headers=my_headers)
s = response.json()
CodePudding user response:
Use can use datetime library provided by python to achieve that.
This is how your code will look like. I have intentionally made the code a bit long, so that you can understand what is happening on each line. This can undoubtedly be done is lesser lines of code.
import requests
from datetime import datetime, timedelta
base_url = 'http://172.24.105.27:8092/Co=LT'
start_date_time = datetime.now() - timedelta(days=7)
end_date_time = datetime.now()
url = f'{base_url}&StartDate={start_date_time.date()}&EndDate={end_date_time.date()}'
print(url)
response = requests.get(url, headers=<your_headers_dict_here>)
print(response)
Sample URL that got formed
http://172.24.105.27:8092/Co=LT&StartDate=2022-08-11&EndDate=2022-08-18