代码之家  ›  专栏  ›  技术社区  ›  Hani Gotc

检查月份的日期是否在两个月之间

  •  -1
  • Hani Gotc  · 技术社区  · 7 年前

    (month,day) 在两个月之间 不管是哪一年 。我在建模方面遇到了问题 .我试着在13岁之前代表1月,但我被卡住了。


    返回值

    • 3. =6月25日至8月22日
    • 2.
    • =9月1日至3月31日或11月1日至12月16日或1月2日至3月31日
    • 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 回复  |  直到 4 年前
        1
  •  2
  •   Adam Smith jeffpkamp    7 年前

    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