Ben Pickering
Ben Pickering

Reputation: 99

Unexpected output from datetime double loop in python

I have a set of directories named as dates in yyyy-mm-dd format. Inside are 1440 files, one for each minute of the day in the format NNyyyymmddHHMM.txt. I want to write a loop to check the contents of these files one by one. To do this I am making a loop of dates which works fine. When I try to pass the date to the second loop to generate the filenames, I get 1440 filenames all for midnight on the date. Doing the second loop by itself and giving it a date works correctly though. So there is an issue when the date from the first loop is passed to the second loop.

Filename loop working correctly by itself:

from datetime import timedelta, datetime

def filerange(date):
    for i in range (0,1440):
        yield date + timedelta(minutes=i)

date = datetime(2017, 2, 10)

for file in filerange(date):
    print ((date.strftime("%Y-%m-%d")) + "/01" + file.strftime("%Y%m%d%H%M" + ".txt"))

Output:

2017-02-10/01201702100000.txt

2017-02-10/01201702100001.txt

2017-02-10/01201702100002.txt

...

Date loop working correctly by itself:

from datetime import timedelta, date, datetime

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = date(2017, 2, 10)
end_date = date(2017, 2, 13)

for date in daterange(start_date, end_date):
    print (date)

Output:

2017-02-10

2017-02-11

2017-02-12

But when I combine the two loops, an error occurs:

from datetime import timedelta, date, datetime

def daterange(start_date, end_date):
    for n in range(int ((end_date - start_date).days)):
        yield start_date + timedelta(n)
        
def filerange(date):
    for i in range (0,1440):
        yield date + timedelta(minutes=i)

start_date = date(2017, 2, 10)
end_date = date(2017, 2, 13)

for date in daterange(start_date, end_date):
    for file in filerange(date):
        print ((date.strftime("%Y-%m-%d")) + "/01" + file.strftime("%Y%m%d%H%M" + ".txt"))

Output:

2017-02-10/01201702100000.txt

2017-02-10/01201702100000.txt

2017-02-10/01201702100000.txt

This occurs 1440 times and then the date progresses to

2017-02-11/01201702110000.txt

It seems to me the timedelta adds the minutes correctly but because the format is daily %Y %m %d it doesn't keep the minute information so when I tell it to display in format with minutes and seconds, it is 00:00

Any ideas?

Upvotes: 0

Views: 58

Answers (1)

Ben Pickering
Ben Pickering

Reputation: 99

I had been using date to input the start and end dates for the date function. To get the filename loop to work on it's own I used datetime to input the date.

Using datetime to enter date range in the double loop works.

Upvotes: 1

Related Questions