Replace dates on a url which are saved on a list

Viewed 57

I have a list [ ] with dates, saved as strings (2020-12-01 to 2020-12-31). I also have the following url:

"https://api.opap.gr/draws/v3.0/1100/draw-date/{date1:%Y-%m-%d}/{date1:%Y-%m-%d}/draw-id"

I want to run a "for loop" in which it will replaces the {date1:%Y-%m-%d} for every element (date) of the list. So far, I have created the following code which creates "ValueError: Invalid format specifier".

from datetime import date, timedelta, datetime
import json, requests

def days_cur_month():
    d1 = date(2020, 12, 1)
    d2 = date(2020, 12, 31)
    delta = d2 - d1

    return [(d1 + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(delta.days + 1)]

print(days_cur_month())

fmt= "https://api.opap.gr/draws/v3.0/1100/draw-date/{date1:%Y-%m-%d}/{date1:%Y-%m-%d}/draw-id"

draws=[]
for i in (days_cur_month()):
    
    url = fmt.format(date1=i)
    r=requests.get(url2)
    html=r.text
    drawIds=json.loads(html)
    print(drawIds)

Is there any way to do this?

1 Answers

Remove .strftime('%Y-%m-%d') when using str.format with conversion

Ex:

from datetime import date, timedelta, datetime
import json, requests

def days_cur_month():
    d1 = date(2020, 12, 1)
    d2 = date(2020, 12, 31)
    delta = d2 - d1

    return [(d1 + timedelta(days=i)) for i in range(delta.days + 1)]


fmt= "https://api.opap.gr/draws/v3.0/1100/draw-date/{date1:%Y-%m-%d}/{date1:%Y-%m-%d}/draw-id"

draws=[]
for i in (days_cur_month()):
    url = fmt.format(date1=i)
    print(url)

Output:

https://api.opap.gr/draws/v3.0/1100/draw-date/2020-12-27/2020-12-27/draw-id
https://api.opap.gr/draws/v3.0/1100/draw-date/2020-12-28/2020-12-28/draw-id
https://api.opap.gr/draws/v3.0/1100/draw-date/2020-12-29/2020-12-29/draw-id
https://api.opap.gr/draws/v3.0/1100/draw-date/2020-12-30/2020-12-30/draw-id
https://api.opap.gr/draws/v3.0/1100/draw-date/2020-12-31/2020-12-31/draw-id

Or if you need to use .strftime('%Y-%m-%d') Then change fmt to

fmt= "https://api.opap.gr/draws/v3.0/1100/draw-date/{date1}/{date1}/draw-id"
Related