Python calendar.isleap() Examples

The following are 30 code examples of calendar.isleap(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module calendar , or try the search function .
Example #1
Source File: date.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def get_date_range_hours_from_year(year):
    """
    creates date range in hours for the year excluding leap day
    :param year: year of date range
    :type year: int
    :return: pd.date_range with 8760 values
    :rtype: pandas.data_range
    """

    date_range = pd.date_range(start=str(year), end=str(year + 1), freq='H', closed='left')

    # Check if leap year and remove extra day
    if isleap(year):
        date_range = date_range[~((date_range.month == 2) & (date_range.day == 29))]

    return date_range 
Example #2
Source File: solve.py    From programming-challenges with GNU General Public License v2.0 6 votes vote down vote up
def main():
  MONTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  
  d1 = 2 # Tuesday
  c = 0
  
  for year in range(1901, 2001):
    if calendar.isleap(year):
      MONTHS[1] = 29
    else:
      MONTHS[1] = 28
    
    for month in range(12):
      if (d1 == 0):
        c = c+1
        print([c, 'month after:', year, month])
      d1 = (d1 + MONTHS[month]) % 7
     
  print (c) 
Example #3
Source File: dateformat.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #4
Source File: dateformat.py    From python with Apache License 2.0 6 votes vote down vote up
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 
Example #5
Source File: program7.py    From python-gui-demos with MIT License 6 votes vote down vote up
def getDOB(self):
        year = self.getyear()
        month = self.getmonth()
        
        if calendar.isleap(year) and month=='February':
            self.lastday =  29
        elif not calendar.isleap(year) and month=='February':
            self.lastday = 28
        elif month in ('January', 'March', 'May', 'July', 'August', 'October', 'December'):
            self.lastday = 31
        elif month in ('April', 'June', 'September', 'November'):
            self.lastday = 30
        else:
            self.lastday = -1
        
        if self.getdate() > self.lastday or self.getdate()<1 or self.lastday == -1:
            date = -1
        else:
            date = self.getdate()
        
        if year != -1 and month != -1 and date != -1:
            self.displaydob.config(text = '{0} {1}, {2}'.format(month, date, year))
        else:
            self.displaydob.config(text = "Invalid Date") 
Example #6
Source File: test_license.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def test_simple_model_with_annual_licence_multi_year(simple_linear_model):
    """ Test the AnnualLicense over multiple years
    """
    import pandas as pd
    import datetime, calendar
    m = simple_linear_model
    # Modify model to run for 3 years of non-leap years at 30 day time-step.
    m.timestepper.start = pd.to_datetime('2017-1-1')
    m.timestepper.end = pd.to_datetime('2020-1-1')
    m.timestepper.delta = datetime.timedelta(30)

    annual_total = 365.0
    lic = AnnualLicense(m, m.nodes["Input"], annual_total)
    # Apply licence to the model
    m.nodes["Input"].max_flow = lic
    m.nodes["Output"].max_flow = 10.0
    m.nodes["Output"].cost = -10.0
    m.setup()

    for i in range(len(m.timestepper)):
        m.step()
        days_in_year = 365 + int(calendar.isleap(m.timestepper.current.datetime.year))
        assert_allclose(m.nodes["Output"].flow, annual_total/days_in_year) 
Example #7
Source File: dateformat.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #8
Source File: dateformat.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: dateformat.py    From bioforum with MIT License 6 votes vote down vote up
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 
Example #10
Source File: dateformat.py    From Hands-On-Application-Development-with-PyCharm with MIT License 6 votes vote down vote up
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 
Example #11
Source File: _dateparser.py    From gprime with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #12
Source File: http.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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 
Example #13
Source File: formmethod.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #14
Source File: formmethod.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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 
Example #15
Source File: gregorian.py    From convertdate with MIT License 6 votes vote down vote up
def to_jd(year, month, day):
    legal_date(year, month, day)

    if month <= 2:
        leap_adj = 0
    elif isleap(year):
        leap_adj = -1
    else:
        leap_adj = -2

    return (
        EPOCH - 1 + (YEAR_DAYS * (year - 1)) +
        floor((year - 1) / LEAP_CYCLE_YEARS) +
        (-floor((year - 1) / LEAP_SUPPRESSION_YEARS)) +
        floor((year - 1) / INTERCALATION_CYCLE_YEARS) +
        floor((((367 * month) - 362) / 12) + leap_adj + day)
    ) 
Example #16
Source File: positivist.py    From convertdate with MIT License 6 votes vote down vote up
def legal_date(year, month, day):
    '''Checks if a given date is a legal positivist date'''
    try:
        assert year >= 1
        assert 0 < month <= 14
        assert 0 < day <= 28
        if month == 14:
            if isleap(year + YEAR_EPOCH - 1):
                assert day <= 2
            else:
                assert day == 1

    except AssertionError:
        raise ValueError("Invalid Positivist date: ({}, {}, {})".format(year, month, day))

    return True 
Example #17
Source File: positivist.py    From convertdate with MIT License 6 votes vote down vote up
def dayname(year, month, day):
    '''
    Give the name of the month and day for a given date.

    Returns:
        tuple month_name, day_name
    '''
    legal_date(year, month, day)

    yearday = (month - 1) * 28 + day

    if isleap(year + YEAR_EPOCH - 1):
        dname = data.day_names_leap[yearday - 1]
    else:
        dname = data.day_names[yearday - 1]

    return MONTHS[month - 1], dname 
Example #18
Source File: account_asset.py    From LibrERP with GNU Affero General Public License v3.0 6 votes vote down vote up
def _get_fy_duration_factor(self, cr, uid, entry, asset, firstyear, context=None):
        """ localization: override this method to change the logic used to calculate the impact of extended/shortened fiscal years """
        duration_factor = 1.0
        fy_id = entry['fy_id']
        if asset.prorata:
            if firstyear:
                depreciation_date_start = datetime.strptime(asset.date_start, '%Y-%m-%d')
                fy_date_stop = entry['date_stop']
                first_fy_asset_days = (fy_date_stop - depreciation_date_start).days + 1
                if fy_id:
                    first_fy_duration = self._get_fy_duration(cr, uid, fy_id, option='days')
                    first_fy_year_factor = self._get_fy_duration(cr, uid, fy_id, option='years')
                    duration_factor = float(first_fy_asset_days) / first_fy_duration * first_fy_year_factor
                else:
                    first_fy_duration = calendar.isleap(entry['date_start'].year) and 366 or 365
                    duration_factor = float(first_fy_asset_days) / first_fy_duration
            elif fy_id:
                duration_factor = self._get_fy_duration(cr, uid, fy_id, option='years')
        elif fy_id:
            fy_months = self._get_fy_duration(cr, uid, fy_id, option='months')
            duration_factor = float(fy_months) / 12
        return duration_factor 
Example #19
Source File: datetime_helpers.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def _make_date_from_match(match):
    g = match.groupdict()
    if g['month']:
        return datetime.date(int(g['year']),
                             int(g['month']),
                             int(g['day']))
    elif g['isoweek']:
        return date_by_isoweekday(int(g['year']),
                                  int(g['isoweek']),
                                  int(g['isoweekday']))
    else:
        year = int(g['year'])
        ordinalday = int(g['ordinalday'])
        if not 1 <= ordinalday <= 366:
            raise ValueError('ordinal day number {!r} is out of '
                             'range 001..366'.format(ordinalday))
        if ordinalday == 366 and not calendar.isleap(year):
            raise ValueError('ordinal day number {!r} is out of range '
                             'for year {!r} (which is not a leap year)'
                             .format(ordinalday, year))
        return date_by_ordinalday(year, ordinalday) 
Example #20
Source File: clearsky.py    From pvlib-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _calendar_month_middles(year):
    """List of middle day of each month, used by Linke turbidity lookup"""
    # remove mdays[0] since January starts at mdays[1]
    # make local copy of mdays since we need to change
    # February for leap years
    mdays = np.array(calendar.mdays[1:])
    ydays = 365
    # handle leap years
    if calendar.isleap(year):
        mdays[1] = mdays[1] + 1
        ydays = 366
    middles = np.concatenate(
        [[-calendar.mdays[-1] / 2.0],  # Dec last year
         np.cumsum(mdays) - np.array(mdays) / 2.,  # this year
         [ydays + calendar.mdays[1] / 2.0]])  # Jan next year
    return middles 
Example #21
Source File: createDatabase.py    From Fraud-Analysis with MIT License 6 votes vote down vote up
def date_between(s, e):
    y = randint(s.year, e.year)
    m = randint(1, 12)
    d = randint(1, 30)

    if calendar.isleap(y):
        if m == 2:
            d = randint(1, 29)

    if m == 2:
        d = randint(1, 28)

    h = randint(0, 12)
    i = randint(0, 59)
    s = randint(0, 59)

    return datetime(y, m, d, h, i, s) 
Example #22
Source File: createDatabase.py    From Fraud-Analysis with MIT License 6 votes vote down vote up
def random_date():
    y = randint(1920, 1999)
    m = randint(1, 12)
    d = randint(1, 30)
    if calendar.isleap(y):
        if m == 2:
            d = randint(1, 29)

    if m == 2:
        d = randint(1, 28)

    h = randint(0, 12)
    i = randint(0, 59)
    s = randint(0, 59)

    return datetime(y, m, d, h, i, s) 
Example #23
Source File: http.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #24
Source File: dateformat.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def L(self):
        "Boolean for whether it is a leap year; i.e. True or False"
        return calendar.isleap(self.data.year) 
Example #25
Source File: indian_civil.py    From convertdate with MIT License 5 votes vote down vote up
def to_jd(year, month, day):
    '''Obtain Julian day for Indian Civil date'''

    gyear = year + 78
    leap = isleap(gyear)
    # // Is this a leap year ?

    # 22 - leap = 21 if leap, 22 non-leap
    start = gregorian.to_jd(gyear, 3, 22 - leap)
    if leap:
        Caitra = 31
    else:
        Caitra = 30

    if month == 1:
        jd = start + (day - 1)
    else:
        jd = start + Caitra
        m = month - 2
        m = min(m, 5)
        jd += m * 31
        if month >= 8:
            m = month - 7
            jd += m * 30

        jd += day - 1

    return jd 
Example #26
Source File: ordinal.py    From convertdate with MIT License 5 votes vote down vote up
def to_gregorian(year, dayofyear):
    leap = isleap(year)

    if dayofyear < 59 + leap:
        leap_adj = 0
    elif leap:
        leap_adj = 1
    else:
        leap_adj = 2

    month = trunc((((dayofyear - 1 + leap_adj) * 12) + 373) / 367)

    startofmonth = from_gregorian(year, month, 1)

    return year, month, dayofyear - startofmonth[1] + 1 
Example #27
Source File: ordinal.py    From convertdate with MIT License 5 votes vote down vote up
def from_gregorian(year, month, day):
    m = month + 1

    if m <= 3:
        m = m + 12

    leap = isleap(year)

    t = (trunc(30.6 * m) + day - 122 + 59 + leap) % (365 + leap)

    return year, t 
Example #28
Source File: test_calendar.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
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) 
Example #29
Source File: dateformat.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def L(self):
        "Boolean for whether it is a leap year; i.e. True or False"
        return calendar.isleap(self.data.year) 
Example #30
Source File: client.py    From aioftp with Apache License 2.0 5 votes vote down vote up
def parse_ls_date(cls, s, *, now=None):
        """
        Parsing dates from the ls unix utility. For example,
        "Nov 18  1958", "Jan 03 2018", and "Nov 18 12:29".

        :param s: ls date
        :type s: :py:class:`str`

        :rtype: :py:class:`str`
        """
        with setlocale("C"):
            try:
                if now is None:
                    now = datetime.datetime.now()
                if s.startswith('Feb 29'):
                    # Need to find the nearest previous leap year
                    prev_leap_year = now.year
                    while not calendar.isleap(prev_leap_year):
                        prev_leap_year -= 1
                    d = datetime.datetime.strptime(
                        f"{prev_leap_year} {s}", "%Y %b %d %H:%M"
                    )
                    # Check if it's next leap year
                    diff = (now - d).total_seconds()
                    if diff > TWO_YEARS_IN_SECONDS:
                        d = d.replace(year=prev_leap_year + 4)
                else:
                    d = datetime.datetime.strptime(s, "%b %d %H:%M")
                    d = d.replace(year=now.year)
                    diff = (now - d).total_seconds()
                    if diff > HALF_OF_YEAR_IN_SECONDS:
                        d = d.replace(year=now.year + 1)
                    elif diff < -HALF_OF_YEAR_IN_SECONDS:
                        d = d.replace(year=now.year - 1)
            except ValueError:
                d = datetime.datetime.strptime(s, "%b %d  %Y")
        return cls.format_date_time(d)