我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用calendar.isleap()。
def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number
def coerce(self, args): """Return tuple of ints (year, month, day).""" if tuple(args) == ("", "", "") and self.allowNone: return None try: year, month, day = map(positiveInt, args) except ValueError: raise InputError, "Invalid date" if (month, day) == (2, 29): if not calendar.isleap(year): raise InputError, "%d was not a leap year" % year else: return year, month, day try: mdays = calendar.mdays[month] except IndexError: raise InputError, "Invalid date" if day > mdays: raise InputError, "Invalid date" return year, month, day
def gregorian_valid(date_tuple): """ Checks if date_tuple is a valid date in Gregorian Calendar """ day = date_tuple[0] month = date_tuple[1] valid = True try: if month > 12: valid = False elif calendar.isleap(date_tuple[2]): if day > _leap_days[month-1]: valid = False elif day > _max_days[month-1]: valid = False except: valid = False return valid
def __init__(self, year, seasons=None, holidays=None): if calendar.isleap(year): hoy = 8784 else: hoy = 8760 self.datapath = os.path.join(os.path.dirname(__file__), 'bdew_data') self.date_time_index = pd.date_range( pd.datetime(year, 1, 1, 0), periods=hoy * 4, freq='15Min') if seasons is None: self.seasons = { 'summer1': [5, 15, 9, 14], # summer: 15.05. to 14.09 'transition1': [3, 21, 5, 14], # transition1 :21.03. to 14.05 'transition2': [9, 15, 10, 31], # transition2 :15.09. to 31.10 'winter1': [1, 1, 3, 20], # winter1: 01.01. to 20.03 'winter2': [11, 1, 12, 31], # winter2: 01.11. to 31.12 } else: self.seasons = seasons self.year = year self.slp_frame = self.all_load_profiles(self.date_time_index, holidays=holidays)
def daysInMonth(self, month, year): """ Take the given month (1-12) and a given year (4 digit) return the number of days in the month adjusting for leap year as needed """ result = None debug and log.debug('daysInMonth(%s, %s)', month, year) if month > 0 and month <= 12: result = self._DaysInMonthList[month - 1] if month == 2: if year in self._leapYears: result += 1 else: if calendar.isleap(year): self._leapYears.append(year) result += 1 return result
def daysBetweenDates(year1, month1, day1, year2, month2, day2): dom = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] domleap = [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (isleap(year1) and isleap(year2)): e1 = sum(domleap) + sum(domleap[:month1 - 1]) + day1 e2 = sum(domleap) + sum(domleap[:month2 - 1]) + day2 return e2 - e1 days = 0 if isleap(year1): days += (sum(domleap[month1 - 1:]) - day1) + sum(dom[:month2 - 1]) + day2 elif isleap(year2): days += (sum(dom[month1 - 1:]) - day1) + sum(domleap[:month2 - 1]) + day2 else: days += (sum(dom[month1 - 1:]) - day1) + sum(dom[:month2 - 1]) + day2 for year in range(year1 + 1, year2): if isleap(year): days += sum(domleap) else: days += sum(dom) return days
def increment(self, when): """ Takes a datetime object and if it is in the past compared to the present it will add the defined interval of time to it till it is in the future """ while not self.is_in_future(when): n = now() if self.interval == 'daily': when = when + timedelta(days=1) elif self.interval == 'weekly': when = when + timedelta(days=7) elif self.interval == 'monthly': when = when + timedelta(days=monthrange(n.year, n.month)[1]) elif self.interval == 'yearly': if isleap(n.year) and self.is_in_future(datetime(year=n.year, month=2, day=29)): when = when + timedelta(days=366) else: when = when + timedelta(days=365) return when
def timevect(d_StartDate, d_EndDate, c_TimeFreq, DT=None): f_Time = [] d_Time = [] while d_StartDate <= d_EndDate: d_Time.append(d_StartDate) f_Time.append(date2num(d_StartDate)) f_Date_aux = date2num(d_StartDate) if c_TimeFreq == 'Monthly': DT_aux = monthrange(num2date(f_Date_aux).year, num2date(f_Date_aux).month)[1] DT = dt.timedelta(days=DT_aux) elif c_TimeFreq == 'Yearly': # finding out if it is a leap-year if isleap(d_StartDate.year + 1): DT = dt.timedelta(days=366) else: DT = dt.timedelta(days=365) d_StartDate += DT return f_Time, d_Time
def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year - 1)): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number
def W(self): "ISO-8601 week number of year, weeks starting on Monday" # Algorithm from http://www.personal.ecu.edu/mccartyr/ISOwdALG.txt week_number = None jan1_weekday = self.data.replace(month=1, day=1).weekday() + 1 weekday = self.data.weekday() + 1 day_of_year = self.z() if day_of_year <= (8 - jan1_weekday) and jan1_weekday > 4: if jan1_weekday == 5 or (jan1_weekday == 6 and calendar.isleap(self.data.year-1)): week_number = 53 else: week_number = 52 else: if calendar.isleap(self.data.year): i = 366 else: i = 365 if (i - day_of_year) < (4 - weekday): week_number = 1 else: j = day_of_year + (7 - weekday) + (jan1_weekday - 1) week_number = j // 7 if jan1_weekday > 4: week_number -= 1 return week_number
def fetch_dumps(dump_dir, dumps_to_fetch): # don't try anything in the last month, it might not be online yet last_date = datetime.datetime.today() - datetime.timedelta(30) year = last_date.year if last_date.month <= 2: year -= 1 if calendar.isleap(year): days = 366 else: days = 365 for i in range(dumps_to_fetch): local_path = None remote_path = None while not local_path or os.path.isdir(local_path): random_day = last_date - datetime.timedelta(days=random.randint(1, days)) random_hour = random.randint(1, 24) d = {'year': random_day.year, 'month': random_day.month, 'day': random_day.day, 'hour': random_hour} remote_path = REMOTE_PATH % d local_path = os.path.join(dump_dir, LOCAL_PATH % d) print 'getting', local_path data = requests.get(remote_path).content with file(local_path, 'wb') as fout: fout.write(data)
def coerce(self, args): """Return tuple of ints (year, month, day).""" if tuple(args) == ("", "", "") and self.allowNone: return None try: year, month, day = map(positiveInt, args) except ValueError: raise InputError("Invalid date") if (month, day) == (2, 29): if not calendar.isleap(year): raise InputError("%d was not a leap year" % year) else: return year, month, day try: mdays = calendar.mdays[month] except IndexError: raise InputError("Invalid date") if day > mdays: raise InputError("Invalid date") return year, month, day
def timegm(year, month, day, hour, minute, second): """ Convert time tuple in GMT to seconds since epoch, GMT """ EPOCH = 1970 if year < EPOCH: raise ValueError("Years prior to %d not supported" % (EPOCH,)) assert 1 <= month <= 12 days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
def assert_last_day(self, period_end): # 30 days has september, april, june and november if period_end.month in [9, 4, 6, 11]: self.assertEqual(period_end.day, 30) # all the rest have 31, except for february elif(period_end.month != 2): self.assertEqual(period_end.day, 31) else: if calendar.isleap(period_end.year): self.assertEqual(period_end.day, 29) else: self.assertEqual(period_end.day, 28)
def equation_of_time(self, year, month, day, latitude): """ Description: Subroutine computing the part of the equation of time needed in the computing of the theoritical solar flux Correction originating of the CMC GEM model. Parameters: int nTime : cTime for the correction of the time. Returns: tuple (double fEot, double fR0r, tuple tDeclsc) dEot: Correction for the equation of time dR0r: Corrected solar constant for the equation of time tDeclsc: Declinaison """ # Julian date nJulianDate = self.Julian(year, month, day) # Check if it is a leap year if(calendar.isleap(year)): fDivide = 366.0 else: fDivide = 365.0 # Correction for "equation of time" fA = nJulianDate / fDivide * 2 * pi fR0r = self.__Solcons(fA) * 0.1367e4 fRdecl = 0.412 * math.cos((nJulianDate + 10.0) * 2.0 * pi / fDivide - pi) fDeclsc1 = self.sind(latitude) * math.sin(fRdecl) fDeclsc2 = self.cosd(latitude) * math.cos(fRdecl) tDeclsc = (fDeclsc1, fDeclsc2) # in minutes fEot = 0.002733 - 7.343 * math.sin(fA) + .5519 * math.cos(fA) \ - 9.47 * math.sin(2.0 * fA) - 3.02 * math.cos(2.0 * fA) \ - 0.3289 * math.sin(3. * fA) - 0.07581 * math.cos(3.0 * fA) \ - 0.1935 * math.sin(4.0 * fA) - 0.1245 * math.cos(4.0 * fA) # Express in fraction of hour fEot = fEot / 60.0 # Express in radians fEot = fEot * 15 * pi / 180.0 return (fEot, fR0r, tDeclsc)
def Julian(self, year, month, day): """ Return julian day. """ if calendar.isleap(year): # Bissextil year, 366 days lMonth = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366] else: # Normal year, 365 days lMonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365] nJulian = lMonth[month - 1] + day return nJulian
def L(self): "Boolean for whether it is a leap year; i.e. True or False" return calendar.isleap(self.data.year)
def timegm(year, month, day, hour, minute, second): """Convert time tuple in GMT to seconds since epoch, GMT""" EPOCH = 1970 assert year >= EPOCH assert 1 <= month <= 12 days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
def test_isleap(self): # Make sure that the return is right for a few years, and # ensure that the return values are 1 or 0, not just true or # false (see SF bug #485794). Specific additional tests may # be appropriate; this tests a single "cycle". self.assertEqual(calendar.isleap(2000), 1) self.assertEqual(calendar.isleap(2001), 0) self.assertEqual(calendar.isleap(2002), 0) self.assertEqual(calendar.isleap(2003), 0)
def is_leap_year(self): """ Determines if the instance is a leap year. :rtype: bool """ return calendar.isleap(self.year)
def _change_year(self, dt, year): if dt.month == 2 and dt.day == 29 and not calendar.isleap(year): return dt.replace(year=year, month=2, day=28) return dt.replace(year=year)
def _change_year(self, new_year): dt = self._datetime if dt.month == 2 and dt.day == 29 and not calendar.isleap(new_year): dt = dt.replace(month=2, day=28) self._datetime = dt.replace(year=new_year)
def is_leap_year(year, learn=True): """ ??????? :param year: 2004 :param learn: ????????????? :return: True """ if learn: return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0) else: return calendar.isleap(year)
def test_leap_year(self): for i in range(-3000, 3000): self.failIf(is_leap_year(i, learn=True) != calendar.isleap(i))
def year_days(year): return "{} has {} days".format(year, 365 + isleap(year))
def is_leap_year(year): """Returns True if year is a leap year, otherwise False.""" return calendar.isleap(year)
def leapyear(year, querytype='is'): import calendar querytype == querytype.lower() if querytype == 'is': return calendar.isleap(year) elif querytype == 'closest': return year % 4 # Return A Random String In Hexadecimal
def __add__(self, other): if isinstance(other, relativedelta): return relativedelta(years=other.years+self.years, months=other.months+self.months, days=other.days+self.days, hours=other.hours+self.hours, minutes=other.minutes+self.minutes, seconds=other.seconds+self.seconds, microseconds=(other.microseconds + self.microseconds), leapdays=other.leapdays or self.leapdays, year=other.year or self.year, month=other.month or self.month, day=other.day or self.day, weekday=other.weekday or self.weekday, hour=other.hour or self.hour, minute=other.minute or self.minute, second=other.second or self.second, microsecond=(other.microsecond or self.microsecond)) if not isinstance(other, datetime.date): raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year)+self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth)-1)*7 if nth > 0: jumpdays += (7-ret.weekday()+weekday) % 7 else: jumpdays += (ret.weekday()-weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret
def __radd__(self, other): if not isinstance(other, datetime.date): raise TypeError("unsupported type for add operation") elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year) + self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret
def __radd__(self, other): if not isinstance(other, datetime.date): raise TypeError, "unsupported type for add operation" elif self._has_time and not isinstance(other, datetime.datetime): other = datetime.datetime.fromordinal(other.toordinal()) year = (self.year or other.year) + self.years month = self.month or other.month if self.months: assert 1 <= abs(self.months) <= 12 month += self.months if month > 12: year += 1 month -= 12 elif month < 1: year -= 1 month += 12 day = min(calendar.monthrange(year, month)[1], self.day or other.day) repl = {"year": year, "month": month, "day": day} for attr in ["hour", "minute", "second", "microsecond"]: value = getattr(self, attr) if value is not None: repl[attr] = value days = self.days if self.leapdays and month > 2 and calendar.isleap(year): days += self.leapdays ret = (other.replace(**repl) + datetime.timedelta(days=days, hours=self.hours, minutes=self.minutes, seconds=self.seconds, microseconds=self.microseconds)) if self.weekday: weekday, nth = self.weekday.weekday, self.weekday.n or 1 jumpdays = (abs(nth) - 1) * 7 if nth > 0: jumpdays += (7 - ret.weekday() + weekday) % 7 else: jumpdays += (ret.weekday() - weekday) % 7 jumpdays *= -1 ret += datetime.timedelta(days=jumpdays) return ret