從給定日期範圍篩選日期的星期,日期

開始日期 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

 

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