Python Forum

Full Version: Double for loop with dates in array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a SQLite database that I've selected into an array cursor where each row has a date element. I've already sorted cursor by date.

I effectively have something like:

cursor = [
    [data1, "date", date2, date3],
    [data1, "date", date2, date3],
    [data1, "date", date2, date3],
    [data1, "date", date2, date3]
]
Using two for loops, I want to write a string for each row, group them together by day, and then group and write those days by month per year.

In the end, it should have:

Quote:-> 2020-02.txt

2020-02-01

data
data

2020-02-02

data

2020-02-05

data

-> 2020-03.txt

2020-03-02

data

2020-03-05

data

And so on.

I'm having trouble how to actually structure the for loops to end the "day" and begin another "day", and the same for a "month".

For now, all I have is:
    date_test = date.fromisoformat(cursor[0][2])
    for idx, val in enumerate(sorted(cursor, key=lambda row: row[2])):
        # Check if the year is different
        if date_test.strftime("%Y") != date.fromisoformat(val[2]).strftime("%Y"):
            # Check if month is different...
            pass
I've written some code that does the work but it is horribly structured:

    cursor.execute("""SELECT 
*
FROM log""")
    records = cursor.fetchall()
    date_index = date.fromisoformat(records[0][2])
    log_file = open("{}.txt".format(date_index.strftime("%Y-%m")), "w")
    log_file.write("""b{}/b:

list
""".format(date_index.strftime("%Y-%m-%d")))
    for idx, val in enumerate(sorted(records, key=lambda row: row[2])):
        date_val = date.fromisoformat(val[2])
        print(date_index, date_val)
        
        # Check if the date is different
        if date_index != date_val:
            print("DEBUG: Date changed")
            
            # Check if day is different so we closed the list.
            if date_index.day != date_val.day:
                log_file.write("""/list

""")
                print("DEBUG: Day changed")
                
            # The month or year is different so we close the file and open an new one
            if date_index.year != date_val.year or date_index.month != date_val.month:
                log_file.close()
                log_file = open("{}.txt".format(date_val.strftime("%Y-%m")), "w")
                log_file.write("""b{}/b:
            
list
""".format(date_val.strftime("%Y-%m-%d")))
                print("DEBUG: month or year changed")
            if date_index.year == date_val.year and date_index.month == date_val.month:
            # The month and year is the same so we open a new list for this day
                log_file.write("""b{}/b:
            
list
""".format(date_val.strftime("%Y-%m-%d")))
            date_index = date_val
        print(val, idx)
        log_file.write(''.join('{}'.format(val)))