python由当前时间计算上周一、周日的日期时间

1、法一

导入datetime包即可;

第二行使用了datetime进行相加,所以传参也得使用datetime进行封装,这样类型才会想等,如:

datetime.datetime.strptime("2023-04-24", '%Y-%m-%d'))

计算周一和周日代码实现:

def get_last_monday_sunday(today_time):
    monday, sunday = today_time + datetime.timedelta(days=-7), today_time + datetime.timedelta(days=-7)
    one_day = datetime.timedelta(days=1)
    while monday.weekday() != 0:
        monday -= one_day
    while sunday.weekday() != 6:
        sunday += one_day

    return str(monday.strftime('%Y%m%d'))[0:8], str(sunday.strftime('%Y%m%d'))[0:8]

2、法二(更简单)

逻辑:当天时间-当前周几-1或7

import copy
import datetime

if __name__ == '__main__':
  now = datetime.datetime.now()
  print(now) # 2023-04-21 17:25:29.433232 
  print(datetime.timedelta(now.weekday())) # 4 days, 0:00:00
  print(datetime.timedelta(days=7)) # 7 days, 0:00:00

  print("上周日时间是:",datetime.datetime.strftime(now - datetime.timedelta(now.weekday()) - datetime.timedelta(days=1),
                                   "%Y-%m-%d")) # 上周日时间是: 2023-04-16
  print("上周一时间是:",datetime.datetime.strftime(now - datetime.timedelta(now.weekday()) - datetime.timedelta(days=7),
                                   "%Y-%m-%d")) # 上周一时间是: 2023-04-10


你可能感兴趣的:(python)