Loop through user-defined dates in Python

Viewed 46

I've done some searches with this and haven't quite found something that would be applicable for what I need to do. Had this been PHP, I think I might have figured it out. But I am completely new to Python.

I have a crawling script where I want the user to be able to input a year and a month. The script would then loop through each month (if providing more than one) and then each year (if providing more than one). The two variables FiledStartDate and FiledEndDate MUST exist, as they are sent via payload in the post request.

I could get this to work using single years and single months. However, I need to go beyond just single year and month.

Note: I didn't forget the Leap Year. If someone could include that, it would be great. Otherwise, I think with a working code, I can figure out how to deal with that.

Obviously, the below example code doesn't work. But hopefully it demonstrates what I want to do.

Thanks in advance

years = '2020'
months = ['01', '02', '03']

for year in years:
    for month in months:
        if month == '01':
            FiledStartDate = year + '-01-01'
            FiledEndDate = year + '-01-31'

        if month == '02':
            FiledStartDate = year + '-02-01'
            FiledEndDate = year + '-02-28'

        if month == '03':
            FiledStartDate = year + '-03-01'
            FiledEndDate = year + '-03-31'

        if month == '04':
            FiledStartDate = year + '-04-01'
            FiledEndDate = year + '-04-30'

    do(something)
redo(something)
1 Answers

Of course you will need to account for incorrect input, if such occurs (exceptions), otherwise simple solution

from datetime import datetime, timedelta
years = ['2020']
months = ['01', '02', '03']

for year in years:
    for month in months:
        FiledStartDate = datetime(int(year), int(month), 1)
        FiledEndDate   = datetime(int(year), int(month) + 1, 1) - timedelta(1)
        print(FiledStartDate, FiledEndDate)
...
2020-01-01 00:00:00 2020-01-31 00:00:00
2020-02-01 00:00:00 2020-02-29 00:00:00
2020-03-01 00:00:00 2020-03-31 00:00:00
Related