python 获取前一天或前N天的日期

  简单实现

   import datetime
   # 获取前1天或N天的日期,beforeOfDay=1:前1天;beforeOfDay=N:前N天
    def getdate(self,beforeOfDay):
        today = datetime.datetime.now()
        # 计算偏移量
        offset = datetime.timedelta(days=-beforeOfDay)
        # 获取想要的日期的时间
        re_date = (today + offset).strftime('%Y-%m-%d')
        return re_date

    # 获取前一周的所有日期(weeks=1),获取前N周的所有日期(weeks=N)
    def getBeforeWeekDays(self,weeks=1):
        # 0,1,2,3,4,5,6,分别对应周一到周日
        week = datetime.datetime.now().weekday()
        days_list = []
        start = 7 * weeks +  week
        end = week
        for index in range(start, end, -1):
            day =self.getdate(index) print(day)
  
  #测试
  #getBeforeWeekDays(1)

   2019-01-07
    2019-01-08
    2019-01-09
    2019-01-10
    2019-01-11
    2019-01-12
    2019-01-13

转载于:https://www.cnblogs.com/shaosks/p/10286515.html

你可能感兴趣的:(python 获取前一天或前N天的日期)