检查月中的某一天是否在两个月之间

时间:2017-07-17 17:52:35

标签: python python-datetime

我想检查(month,day)是否在两个月之间,无论年份。我在模拟 1月的月份时遇到了问题。我试图在1月13日代表我,但我被卡住了。

返回值

  • 3 = 25JUN到22AUG之间
  • 2 = 01APR-24JUN或22AUG-31OCT或17DEC-01JAN之间
  • 1 =在01SEP-31MAR或01NOV-16DEC或02JAN-31MAR之间
  • 0 =我的程序无效,无法找到日期。我被搞砸了

源代码

from datetime import date, datetime, timedelta

def get_season(date):
        month = date.month
        day   = date.day

        if month == 1:
            month = 13

        if (6,25) <= (month, day) <= (8,22):
            return 3

        elif (4, 1) <= (month, day) <= (6,24) or (8, 22) < (month, day) <= (10, 31) or (12,17) <= (month, day) <= (13,1):
            return 2

        elif  (9, 1) <= (month, day) <= (3, 31) or  (11,1) <= (month, day) <= (12, 16) or (13,2) <= (month, day) <= (3, 31):
            return 1
        else:
            return 0

if __name__ == "__main__":

    date = datetime.strptime("2016-02-01",'%Y-%m-%d').date()

    if get_season(date) == 0:
      print "WRONG DOES NOT EXIST THERE!!!!!!!!!!!!!!"

1 个答案:

答案 0 :(得分:3)

我会直接在datetime.date个对象之间进行所有这些比较,并将它们重新编写为一年。

from datetime import date

def get_season(d):

    d = date(year=1900, month=d.month, day=d.day)

    if date(1900, 6, 25) <= d <= date(1900, 8, 22):
        return 3

    elif date(1900, 4, 1) <= d <= date(1900, 6, 24) or \
         date(1900, 8, 22) <= d <= date(1900, 10, 31) or \
         date(1900, 12, 17) <= d <= date(1900 12, 31) or \
         date(1900, 1, 1) == d:
        return 2

    elif date(1900, 9, 1) <= d <= date(1900, 3, 31) or \
         date(1900, 11, 1) <= d <= date(1900, 12, 16) or \
         date(1900, 1, 2) <= d <= date(1900, 3, 31):
        return 1

这也使得创建边界对变得更加容易。

def get_season(d):
    d = date(year=1900, month=d.month, day=d.day)

    boundarydict = {1: [(date(1900, 9, 1), date(1900, 3, 31)),
                        (date(1900, 11, 1), date(1900, 12, 16)),
                        (date(1900, 1, 2), date(1900, 3, 31))],
                    2: [(date(1900, 4, 1), date(1900, 6, 24)),
                        (date(1900, 8, 22), date(1900, 10, 31)),
                        (date(1900, 12, 17), date(1900, 12, 31)),
                        (date(1900, 1, 1), date(1900, 1, 1))], # note this one!
                    3: [(date(1900, 6, 25), date(1900, 8, 22))]}

    for retval, boundaries in boundarydict.values():
        if any(a <= d <= b for a, b in boundaries):
            return retval