从给定日期范围筛选日期的星期,日期

开始日期 2019-01-01 20:15:33  结束日期 2019-12-12 20:13:21

start_date = '2019-01-01'
end_date = '2019-12-12'

# 接收筛选出的日期
days = []
  • 筛选星期(例如:1月1日到12月12日之间的所有的星期六)

# Python中默认0-6表示周一到周日
select_date = [1,6]
for sel in select_date:
    tp = True
#  如果开始日期的星期数大于所选星期数,则从下一个星期数开始
    if sel < start_date.weekday():
        sel += 7
    while tp:
        ce_date = start_date + datetime.timedelta(days=sel - start_date.weekday())
        while ce_date >= end_date:
            if ce_date == end_date:
                days.append(ce_date)
            tp = False
            break
        else:
            days.append(ce_date)
            sel += 7
  • 筛选日子(例如:1月1日到12月12日之间所有的20,25号)

select_date = [20, 25] 
   for sel in select_date:
       start_year = start_date.year
       start_month = start_date.month
       start_day = start_date.day
       end_year = end_date.year
       end_month = end_date.month
       tp = True
       if sel < start_day:
           start_month += 1
       while tp:
           cel_dt = datetime.datetime(start_year, month=start_month, day=sel)
           while cel_dt >= last:
               if cel_dt == last:
                   days.append(cel_dt)
                   tp = False
                   break
           else:
               days.append(cel_dt)
               if start_year < end_year and start_month < 12:
                   start_month += 1
               elif start_year < end_year and start_month == 12:
                   start_year += 1
                   start_month = 1
               elif start_year == end_year and start_month < end_month:
                   start_month += 1
               elif start_year == end_year and start_month >= end_month:
                    break
        else:
            continue

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章