'How to group a table by last day of week using SQL-Alchemy?

I have a SQL table my_table with the following format:

id   |   starttime
-----|--------------
1    |   2021-08-09 01:00:00
14   |   2021-09-01 16:00:00
17   |   2021-11-10 19:00:00
25   |   2022-01-10 10:00:00
35   |   2022-02-08 23:00:00

I want to count the number of records in the above table by week end date. Currently, I'm able to get the results by week number of a year using the following query:

request.dbsession.query(
    label('week', func.extract(
       "week", func.date(my_table.starttime))),
    label('num_records', func.count(my_table.id))
    )
    .group_by('week')
)

which give me results that look like following:

[
   {"week": 36, "num_records": 5},
   {"week": 40, "num_records": 15},
   {"week": 47, "num_records": 15},
   {"week": 1, "num_records": 3},
   {"week": 5, "num_records": 7}
]

Now, how do I instead get the results by week end date in the below format?

[
   {"week": "2021-08-15", "num_records": 5},
   {"week": "2021-09-05", "num_records": 15},
   {"week": "2021-11-14", "num_records": 15},
   {"week": "2022-01-16", "num_records": 3},
   {"week": "2022-02-13", "num_records": 7}
]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source