Python获取前一周的日期

2024-01-02
#Python

代码:

import datetime

def day_get():
    Today = datetime.date.today()
    List = []
    # This is number before today.
    num = 7
    for i in range(num,0,-1):
        Delta = datetime.timedelta(days=i)
        day = Today - Delta
        format_day = day.strftime("%Y-%m-%d")
        List.append(format_day)
    return List

调用:

a = day_get()
for i in range(len(a)):
    print(i, a[i])

运行结果:

0 2023-12-26
1 2023-12-27
2 2023-12-28
3 2023-12-29
4 2023-12-30
5 2023-12-31
6 2024-01-01

参考