I have an app built using Flask, flask_sqlalchemy and sqlite3 db. Am building the analytics page and I want to count number of records in a table for each month. The table with the records has a column DATETIME. I have some code that generates comparison dates for this month and last month -- below
today_date = datetime.now()
first_month_date = today_date.replace(day=1)
end_last_month = first_month_date - timedelta(days=1)
end_last_month_temp = end_last_month
start_last_month = end_last_month_temp.replace(day=1)
Using sqlalchemy filter function, I can filter records for this month using first month date and for last month using the end & start last month variables.
Based on this, I think it would be possible to write a for loop that finds the next date backwards and queries the db for a count of the records. The loop knows when to stop when the encountered records reach the total row count for that table.
I think this is not an effective solution. Are there any ideas on how to count all records in table according to month in a much cleaner fashion? Maybe a less known function in sqlalchemy or even a lambda function to include in the query?