Nested for loop to create list of urls

Question:

I am looking for a way to create a list of urls by modifying the name of the country and the date/time.

For each country, each day and each hour of the day I need to create a unique url.


import datetime

start_date = datetime.date(2019, 4, 4)
end_date = datetime.date(2019, 4, 5)
delta = datetime.timedelta(days=1)

list_of_urls = []

list_of_countries = ['france', 'germany', 'spain']


for country in list_of_countries:
    while start_date <= end_date:
        for hour in range(0, 24, 1):
            base_url = 'https://thewebsite.com/'+ country +'/'+ start_date.strftime("%Y-%m-%d")
            url = base_url + '/' + str(hour) + '/'
            list_of_urls.append(url)
        start_date += delta 

print(list_of_urls)

It must be very basic but I don’t understand why the for loop is applying only to the first country and not the three of them. When printing list_of_urls, only france appears (each day from 0 to 24hours)…

Any help would be greatly appreciated.

Thank you,

Asked By: silkywork

||

Answers:

You need to reset the start date each time through the for loop. Here is the fixed script:

import datetime

start_date = datetime.date(2019, 4, 4)
end_date = datetime.date(2019, 4, 5)
delta = datetime.timedelta(days=1)

list_of_urls = []
list_of_countries = ['france', 'germany', 'spain']

for country in list_of_countries:
    current_date = start_date

    while current_date <= end_date:
        for hour in range(0, 24, 1):
            base_url = 'https://thewebsite.com/'+ country +'/'+ current_date.strftime("%Y-%m-%d")
            url = base_url + '/' + str(hour) + '/'
            list_of_urls.append(url)
        current_date += delta 

print(list_of_urls)
Answered By: Emrah Diril