Exemplo n.º 1
0
def parse_num1(s):
    # match mm/dd
    mat = _num1.match(s)
    year = time.gmtime(time.time())[0]
    if mat is None:
        return None
    smonth = int(mat.group("sm"))
    sday = int(mat.group("sd"))
    if mat.group("sy"):
        year = guess_year(int(mat.group("sy")))
        if isleap(year):
            _mdays = leap_mdays
        else:
            _mdays = mdays
    else:
        # assume day and month given
        if isleap(year):
            _mdays = leap_mdays
        else:
            _mdays = mdays

    if 1 > sday or smonth < len(_mdays) and sday > _mdays[smonth]:
        raise error, "Day of the month out of range: %s" % s
    start = end = time.mktime((year, smonth, sday, 0, 0, 0, 0, 0, 0))
    if _debug > 1:
        print "num1 matched"
    return start, end
Exemplo n.º 2
0
def parse_euro4(s):
    mat = _euro4.match(s)
    if mat is None:
        return None
    smonth = month_num[mat.group("sm").encode("iso-8859-1")]
    emonth = month_num[mat.group("em").encode("iso-8859-1")]

    sday = int(mat.group("sd"))
    syear = guess_year(int(mat.group("sy")))
    if isleap(syear):
        _mdays = leap_mdays
    else:
        _mdays = mdays
    if 1 > sday or sday > _mdays[smonth]:
        raise error, "Day of the month out of range: %s" % s

    eday = int(mat.group("ed"))
    eyear = guess_year(int(mat.group("ey")))
    if isleap(eyear):
        _mdays = leap_mdays
    else:
        _mdays = mdays
    if 1 > eday or eday > _mdays[emonth]:
        raise error, "Day of the month out of range: %s" % s

    start = time.mktime((syear, smonth, sday, 0, 0, 0, 0, 0, 0))
    end = time.mktime((eyear, emonth, eday, 0, 0, 0, 0, 0, 0))
    if _debug > 1:
        print "euro4 matched"
    return start, end
Exemplo n.º 3
0
def parse_amer4(s):
    mat = _amer4.match(s)
    if mat is None:
        return None
    smonth = month_num[mat.group("sm").encode("iso-8859-1")]
    emonth = month_num[mat.group("em").encode("iso-8859-1")]
    sday = int(mat.group("sd"))
    eday = int(mat.group("ed"))

    syear = int(mat.group("sy"))
    if isleap(syear):
        _mdays = leap_mdays
    else:
        _mdays = mdays
    if 1 <= sday <= mdays[smonth]:
        start = time.mktime((syear, smonth, sday, 0, 0, 0, 0, 0, 0))
    else:
        raise error, "Day of the month out of range: %s" % s

    eyear = int(mat.group("ey"))
    if isleap(eyear):
        _mdays = leap_mdays
    if 1 <= eday <= _mdays[emonth]:
        end = time.mktime((eyear, emonth, eday, 0, 0, 0, 0, 0, 0))
    else:
        raise error, "Day of the month out of range: %s" % s
    if _debug > 1:
        print "amer4 matched"
    return start, end
Exemplo n.º 4
0
 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
Exemplo n.º 5
0
 def _addYear(self, aDate):
     if (calendar.isleap(aDate.year) and aDate.month <= 2 and aDate.day <= 28) or (
         calendar.isleap(aDate.year + 1) and aDate.month >= 3
     ):
         days = 366
     else:
         days = 365
     newDate = aDate + timedelta.TimeDelta(days=days)
     if self.sameWeekday:
         # Find the nearest date in newDate's year that is on the right weekday
         weekday, year = aDate.weekday(), newDate.year
         oneDay = timedelta.TimeDelta(days=1)
         newEarlierDate = newLaterDate = newDate
         while newEarlierDate.weekday() != weekday:
             newEarlierDate = newEarlierDate - oneDay
         while newLaterDate.weekday() != weekday:
             newLaterDate = newLaterDate + oneDay
         if newEarlierDate.year != year:
             newDate = newLaterDate
         elif newLaterDate.year != year:
             newDate = newEarlierDate
         elif newDate - newEarlierDate < newLaterDate - newDate:
             newDate = newEarlierDate
         else:
             newDate = newLaterDate
     return newDate
Exemplo n.º 6
0
    def dump(self, year, month) :
        weekName = ['MON','TUE','WED','THU','FRI','SAT','SUN']
        matrix = calendar.monthcalendar(year,month)

        """
        print year, month
        for week in matrix :
            for day in week :
                print '%02s'%(day),
            print
        """
        print

        print '%s (%s) %d\n'%(calendar.month_name[month],month,year)

        for day in weekName :
            print day,
        print
        
        for week in matrix :
            for day in week :
                if day == 0 :
                    print '%03s'%(' '),
                else :
                    print '%03s'%(day),
            print
        print

        print calendar.isleap(year)
        calendar.prmonth(year,month)
Exemplo n.º 7
0
    def checkHolidayDate(self):


        if self.is_only_for_this_year == True:
            if self.is_only_for_this_year == 0:
                raise Warning('Year must must not equal to zero.')
            else:
               is_leapYear = calendar.isleap(self.holiday_year)
        else:
            is_leapYear = calendar.isleap(genx.YEAR_NOW)

        if self.holiday_month == 2:
            int_feb_day = 28
            if is_leapYear == True:
               int_feb_day +=1
            if self.holiday_day <= 0:
                raise ValidationError('Days must not be equal to zero.')
            if self.holiday_day > int_feb_day:
                raise ValidationError('Days exceeded.')
        elif self.holiday_month in(1,3,5,7,8,10,12):
            if self.holiday_day <= 0:
                raise ValidationError('Days must not be equal to zero.')
            if self.holiday_day > 31:
                raise ValidationError('Days exceeded.')
        elif self.holiday_month in(4,6,9,11):
            if self.holiday_day <= 0:
                raise ValidationError('Days must not be equal to zero.')
            if self.holiday_day > 30:
                raise ValidationError('Days exceeded.')
Exemplo n.º 8
0
 def compute_depreciation(self, date, dates):
     """
     Returns the depreciation amount for an asset on a certain date.
     """
     amount = (self.value - self.get_depreciated_amount()
         - self.residual_value)
     if self.depreciation_method == 'linear':
         start_date = max([self.start_date
                 - relativedelta.relativedelta(days=1)]
             + [l.date for l in self.lines])
         first_delta = dates[0] - start_date
         if len(dates) > 1:
             last_delta = dates[-1] - dates[-2]
         else:
             last_delta = first_delta
         if self.frequency == 'monthly':
             _, first_ndays = calendar.monthrange(
                 dates[0].year, dates[0].month)
             _, last_ndays = calendar.monthrange(
                 dates[-1].year, dates[-1].month)
         elif self.frequency == 'yearly':
             first_ndays = 365 + calendar.isleap(dates[0].year)
             last_ndays = 365 + calendar.isleap(dates[-1].year)
         first_ratio = Decimal(first_delta.days) / Decimal(first_ndays)
         last_ratio = Decimal(last_delta.days) / Decimal(last_ndays)
         depreciation = amount / (
             len(dates) - 2 + first_ratio + last_ratio)
         if date == dates[0]:
             depreciation *= first_ratio
         elif date == dates[-1]:
             depreciation *= last_ratio
         return self.company.currency.round(depreciation)
Exemplo n.º 9
0
 def __normalizeDate(self, day, month, year):
 # Returns a valid year, month and day, given a day value that is out
 # of the acceptable range. This is needed so that the correct local
 # date can be determined after adding the local time offset to the
 # UTC time. The time difference may result in the day being shifted,
 # for example Jan 1 may become Jan 0, which needs to be normalized
 # to Dec 31 of the preceding year. This function may also be used to
 # convert a Julian day (1-366) for the given year to a proper year,
 # month and day, if the month is initially set to 1.
     while (month < 1 or
            month > 12 or
            day < 1 or
            day > _month_days[calendar.isleap(year)][month]
           ):
         if month < 1:
             year -= 1
             month += 12
         elif month > 12:
             year += 1
             month -= 12
         elif day < 1:
             month -= 1
             if month == 0:
                 #Special case
                 day += 31
             else:
                 day += _month_days[calendar.isleap(year)][month]
         elif day > _month_days[calendar.isleap(year)][month]:
             day -= _month_days[calendar.isleap(year)][month]
             month += 1
     return year, month, day
def calendar_():
  cal = calendar.month(2017, 6)  # by default w=2 l=1
  print cal  # 2017年6月份日历

  print '--------------------'
  # calendar内置函数
  #calendar of year 2017: c=distance(month); l=line(week); w=distance(day)
  print calendar.calendar(2017, w=2, l=1, c=6)  #lenth(line)= 21* W+18+2* C

  print calendar.firstweekday() # start weekday, 0 by default, i.e. Monday
  # calendar.setfirstweekday(weekday)  # 0(Monday) to 6(Sunday)

  print calendar.isleap(2017) # return True or False
  print calendar.leapdays(2000, 2016) # number of leap years between year 1 and year 2

  print calendar.month(2017, 6)
  print calendar.monthcalendar(2017, 6)

  print calendar.monthrange(2017, 6)  # return (a, b)  a=starting weekday b=days in month

  calendar.prcal(2017, w=2, l=1, c=4)  # equals to print calendar.calendar(2017, w=2, l=1, c=4)
  calendar.prmonth(2017, 6) # equals to print calendar.month(2017, 6)

  print calendar.timegm(time.localtime()) #和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍

  print calendar.weekday(2017, 6, 30) # calendar.weekday(year,month,day) return date code
Exemplo n.º 11
0
def getyrmon(day_of_year,yyyy=2001):
    d1 = datetime.datetime(yyyy,1,1)
    if calendar.isleap(d1.year) and day_of_year > 366:
        raise ValueError, 'not that many days in the year'
    if not calendar.isleap(d1.year) and day_of_year > 365:
        raise ValueError, 'not that many days in the year'
    d2 = d1 + (day_of_year-1)*datetime.timedelta(days=1)
    return d2.month,d2.day
Exemplo n.º 12
0
def timesince(d, now=None, reversed=False, time_strings=None):
    """
    Take two datetime objects and return the time between d and now as a nicely
    formatted string, e.g. "10 minutes". If d occurs after now, return
    "0 minutes".

    Units used are years, months, weeks, days, hours, and minutes.
    Seconds and microseconds are ignored.  Up to two adjacent units will be
    displayed.  For example, "2 weeks, 3 days" and "1 year, 3 months" are
    possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not.

    `time_strings` is an optional dict of strings to replace the default
    TIME_STRINGS dict.

    Adapted from
    http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    if time_strings is None:
        time_strings = TIME_STRINGS

    # Convert datetime.date to datetime.datetime for comparison.
    if not isinstance(d, datetime.datetime):
        d = datetime.datetime(d.year, d.month, d.day)
    if now and not isinstance(now, datetime.datetime):
        now = datetime.datetime(now.year, now.month, now.day)

    now = now or datetime.datetime.now(utc if is_aware(d) else None)

    if reversed:
        d, now = now, d
    delta = now - d

    # Deal with leapyears by subtracing the number of leapdays
    leapdays = calendar.leapdays(d.year, now.year)
    if leapdays != 0:
        if calendar.isleap(d.year):
            leapdays -= 1
        elif calendar.isleap(now.year):
            leapdays += 1
    delta -= datetime.timedelta(leapdays)

    # ignore microseconds
    since = delta.days * 24 * 60 * 60 + delta.seconds
    if since <= 0:
        # d is in the future compared to now, stop processing.
        return avoid_wrapping(gettext('0 minutes'))
    for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS):
        count = since // seconds
        if count != 0:
            break
    result = avoid_wrapping(time_strings[name] % count)
    if i + 1 < len(TIMESINCE_CHUNKS):
        # Now get the second item
        seconds2, name2 = TIMESINCE_CHUNKS[i + 1]
        count2 = (since - (seconds * count)) // seconds2
        if count2 != 0:
            result += gettext(', ') + avoid_wrapping(time_strings[name2] % count2)
    return result
Exemplo n.º 13
0
def last_of_month(dt):
	if dt.month == 1 or dt.month == 3 or dt.month == 5 or dt.month == 7 or dt.month == 8 or dt.month == 10 or dt.month == 12:
		return date(dt.year,dt.month,31)
	elif dt.month == 4 or dt.month == 6 or dt.month == 9 or dt.month == 11:
		return date(dt.year,dt.month,30)
	elif dt.month == 2 and isleap(dt.year) == True:
		return date(dt.year,dt.month,29)
	elif dt.month == 2 and isleap(dt.year) == False:
		return date(dt.year,dt.month,28)
Exemplo n.º 14
0
def get_canonical_date(arg):
    """
    Transform "arg" in a valid yyyy-mm-dd date or return None.
    "arg" can be a yyyy-mm-dd, yyyymmdd, mmdd, today, next week,
    next month, next year, or a weekday name.
    Literals are accepted both in english and in the locale language.
    When clashes occur the locale takes precedence.
    """
    today = date.today()
    #FIXME: there surely exist a way to get day names from the  datetime
    #       or time module.
    day_names = ["monday", "tuesday", "wednesday", \
                 "thursday", "friday", "saturday", \
                 "sunday"]
    day_names_localized = [_("monday"), _("tuesday"), _("wednesday"), \
                 _("thursday"), _("friday"), _("saturday"), \
                 _("sunday")]
    delta_day_names = {"today":      0, \
                       "tomorrow":   1, \
                       "next week":  7, \
                       "next month": calendar.mdays[today.month], \
                       "next year":  365 + int(calendar.isleap(today.year))}
    delta_day_names_localized = \
                      {_("today"):      0, \
                       _("tomorrow"):   1, \
                       _("next week"):  7, \
                       _("next month"): calendar.mdays[today.month], \
                       _("next year"):  365 + int(calendar.isleap(today.year))}
    ### String sanitization
    arg = arg.lower()
    ### Conversion
    #yyyymmdd and mmdd
    if arg.isdigit():
        if len(arg) == 4:
            arg = str(date.today().year) + arg
        assert(len(arg) == 8)
        arg = "%s-%s-%s" % (arg[:4], arg[4:6], arg[6:])
    #today, tomorrow, next {week, months, year}
    elif arg in delta_day_names.keys() or \
         arg in delta_day_names_localized.keys():
        if arg in delta_day_names:
            delta = delta_day_names[arg]
        else:
            delta = delta_day_names_localized[arg]
        arg = (today + timedelta(days = delta)).isoformat()
    elif arg in day_names or arg in day_names_localized:
        if arg in day_names:
            arg_day = day_names.index(arg)
        else:
            arg_day = day_names_localized.index(arg)
        today_day = today.weekday()
        next_date = timedelta(days = arg_day - today_day + \
                          7 * int(arg_day <= today_day)) + today
        arg = "%i-%i-%i" % (next_date.year,  \
                            next_date.month, \
                            next_date.day)
    return strtodate(arg)
Exemplo n.º 15
0
	def computeHijraDate(self, date):
		timeTuple = date.timetuple()
		year    = date.year
		#month   = date.month
		#day     = date.day
		hours   = timeTuple[3]
		minutes = timeTuple[4]
		seconds = timeTuple[5]

		deltaDays = self.jDate - self.julian(year, 1, 1)
		fractionalYear = (year + deltaDays / (365 + calendar.isleap(year)) - 621.578082192) / 0.97022298
		fractionalYear += numpy.floor(numpy.fabs(fractionalYear) / 3000) * 30 / 10631
		fractionalDay = fractionalYear - numpy.floor(fractionalYear)

		hijraYear = fractionalYear - fractionalDay

		if ((fractionalDay * 10631 / 30) - numpy.floor(fractionalDay * 10631 / 30) < 0.5):
		    fractionalDay = numpy.floor(fractionalDay * 10631 / 30) + 1
		else: fractionalDay = numpy.floor(fractionalDay * 10631 / 30) + 2

		gregorianYear = hijraYear * 0.970224044 + 621.574981435
		gregorianFractionalDay = gregorianYear - numpy.floor(gregorianYear)
		gregorianYear -= gregorianFractionalDay
		gregorianDay = numpy.floor((365 + calendar.isleap(gregorianYear)) * gregorianFractionalDay) + 1
		gregorianYear += gregorianDay / (365 + calendar.isleap(gregorianYear))
		hijraFractionalYear = (gregorianYear - 621.574981435) / 0.970224044
		hijraFractionalDay = hijraFractionalYear - numpy.floor(hijraFractionalYear)
		hijraDay = hijraFractionalDay * 10631 / 30 + 1;
		hijraMonth = 1
		hijraFractionalDay = 1
		while hijraFractionalDay < fractionalDay:
		    hijraDay += 1
		    hijraFractionalDay += 1
		    if hijraDay >= self.fractionalMonth:
		        hijraDay = hijraDay - self.fractionalMonth
		        hijraMonth += 1
		hijraDay = numpy.floor(hijraDay) + 1
		if hijraMonth == 13:
		    hijraMonth = 1
		    hijraYear += 1
		partDay = (hours + minutes / 60 + seconds / 3600) / 24
		precise = self.pcision(self.jDate + partDay)
		if hijraDay != precise:
		    if (hijraDay == 1) and (precise > 28):
		        hijraMonth -= 1
		        if hijraMonth == 0: 
		            hijraMonth = 12
		            hijraYear -= 1
		    elif (hijraDay > 28) and (precise < 3):
		        hijraMonth += 1
		        if hijraMonth == 13:
		            hijraMonth = 1
		            hijraYear += 1
		hijraDay = precise
		if hijraYear < 1: hijraYear -= 1

		return str(hijraDay) + "\n" + self.months[hijraMonth - 1] + "\n" + str(int(hijraYear)) + "\n" + self.weekDays[timeTuple[6]]
Exemplo n.º 16
0
 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 main():
  ticks=time.time()
  print ticks
  localtime=time.asctime(time.localtime(time.time()))
  print localtime
  print time.strftime("%Y-%m-%d%H:%M:%S",time.localtime())
  import calendar
  cal=calendar.month(2017,6)
  print cal
  print calendar.isleap(2017)
def main():
    
    # Set the seed so we can repeat this if required
    np.random.seed(42)
    
    start_yr = 1960 # weird stuff in the 1950s AWAP data
    end_yr = 1990
    out_yrs = end_yr - start_yr
    yrs = np.arange(start_yr, end_yr+1)
    
    # preserve leap yrs, so find them first
    leapyrs = np.zeros(0)
    for yr in yrs:
        if calendar.isleap(yr):    
            leapyrs = np.append(leapyrs, yr)
        #print >>f, float(yr) 
    
    # However we don't want the leapyrs in the sequence, so exclude them
    yrs = np.array([yrs[i] for i, yr in enumerate(yrs) if yr not in leapyrs])
    
    shuff_years = randomise_array(out_yrs, yrs)
    shuff_years_leap = randomise_array(out_yrs, leapyrs)
    
    
    i = 0
    for yr in np.arange(start_yr, end_yr):
        
        if i == 0:
            prev_yr_leap = 1666 # anything not in the sequence
            prev_yr = 1666 # anything not in the sequence
            
        if calendar.isleap(yr):
            out_yr = shuff_years_leap[i]
           
            # Make sure we don't get the same year twice
            while prev_yr_leap == int(out_yr):
                i += 1
                out_yr = shuff_years_leap[i]
                
            print "%d," % (int(out_yr)),
            prev_yr_leap = shuff_years_leap[i]
        else:
            out_yr = shuff_years[i]
            
            # Make sure we don't get the same year twice
            while prev_yr == int(out_yr):
                i += 1
                out_yr = shuff_years[i]
            
            print "%d," % (int(out_yr)),
            prev_yr = shuff_years[i]
        
        i += 1
    print
Exemplo n.º 19
0
def relative_day(week_start, which_day):
    d_year, d_doy = week_start[0], week_start[-2]
    doy = d_doy + which_day
    if doy < 1:
        d_year -= 1
        doy += 365 + int (calendar.isleap (d_year))
    elif doy > 365 + int (calendar.isleap (d_year)):
        doy -= 365 + int (calendar.isleap (d_year))
        d_year += 1
    day = time.strptime (str(d_year) + str(doy), "%Y%j")
    return day
Exemplo n.º 20
0
def is_leap(year=None):
    """
    判断闰年:
    四年一闰,百年不闰,四百年再闰
    None 返回当前年是否为闰年
    非int类型 返回False
    """
    if year is None:
        return calendar.isleap(get_current_y())
    if type(year) == int:
        return calendar.isleap(year)
    return False
Exemplo n.º 21
0
def how_many_leap_days(from_date, to_date):
    """Get the number of leap days between two dates

    :param from_date: A datetime object. If only a year is specified, will use
        January 1.
    :type from_date: datetime.datetime, datetime.date
    :param to_date: A datetime object.. If only a year is specified, will use
        January 1.
    :type to_date: datetime.datetime, datetime.date
    :returns: int -- the number of leap days.

    .. versionadded:: 0.3.0
    """
    if isinstance(from_date, int):
        from_date = datetime.date(from_date, 1, 1)

    if isinstance(to_date, int):
        to_date = datetime.date(to_date, 1, 1)

    assert _is_date_type(from_date) and \
        not isinstance(from_date, datetime.time)
    assert _is_date_type(to_date) and not isinstance(to_date, datetime.time)

    # Both `from_date` and `to_date` need to be of the same type. Since both
    # `datetime.date` and `datetime.datetime` will pass the above assertions,
    # cast any `datetime.datetime` values to `datetime.date`.
    if isinstance(from_date, datetime.datetime):
        from_date = from_date.date()
    if isinstance(to_date, datetime.datetime):
        to_date = to_date.date()

    assert from_date <= to_date

    number_of_leaps = calendar.leapdays(from_date.year, to_date.year)

    # `calendar.leapdays()` calculates the number of leap days by using
    # January 1 for the specified years. If `from_date` occurs after
    # February 28 in a leap year, remove one leap day from the total. If
    # `to_date` occurs after February 28 in a leap year, add one leap day to
    # the total.
    if calendar.isleap(from_date.year):
        month, day = from_date.month, from_date.day
        if month > 2 or (month == 2 and day > 28):
            number_of_leaps -= 1

    if calendar.isleap(to_date.year):
        month, day = to_date.month, to_date.day
        if month > 2 or (month == 2 and day > 28):
            number_of_leaps += 1

    return number_of_leaps
Exemplo n.º 22
0
def nextDay(midnightStamp):
    ##incremement to the next day
    
    #determine the month...
    monthCheck = str(midnightStamp)[-4:-2]
    
    #...and year of the timestamp
    yearCheck  = long(str(midnightStamp)[:4])
      
    ##increment year    : +100000000
    ##increment month   : +  1000000
    ##increment day     : +    10000
    ##increment hour    : +      100
    ##reset to midnight : -     2300
    
    ##reset to midnight
    stamp = int(midnightStamp)
    print    str(midnightStamp)[-4:]
    #print "stamp " + str(stamp)

    #handle end of year
    if str(stamp)[-4:] == "1231":
        stamp = int(stamp) + (8870)
        print "new year " + str(stamp)

    #handle non-leap year end of February    
    elif str(stamp)[-4:] == "0228" and not calendar.isleap(yearCheck) and int(monthCheck) == 2: 
        stamp = int(stamp) + (73)         

    #handle leap year end of February    
    elif str(stamp)[-4:] == "0229" and calendar.isleap(yearCheck) and int(monthCheck) == 2:
        stamp = int(stamp) + (72) 
         #decrement the day by 28 (-280000) and increment the month (+1000000)

    #handle end of thirty-day months  
    elif str(stamp)[-2:] == "30" and (int(monthCheck) == 4 or int(monthCheck) == 6 or int(monthCheck) == 9 or int(monthCheck) == 11):        
        stamp = int(stamp) + (71)
         #decrement the day by 29 (-290000) and increment the month (+1000000)

    #handle end of thirty-one-day months (except December)
    elif str(stamp)[-2:] == "31" and (int(monthCheck) == 1 or int(monthCheck) == 3 or int(monthCheck) == 5 or int(monthCheck) == 7 or int(monthCheck) == 8 or int(monthCheck) == 10):        
        stamp = int(stamp) + (70) 
        #decrement the day by 30 (-300000) and increment the month (+1000000)

    #if it's not the end of a month, just increment the day
    else:
        stamp = int(stamp) + 1
    print "stamp " + str(stamp)

    return stamp
Exemplo n.º 23
0
def shire_year_day(gregorian_year, gregorian_day):
    """Return the shire year and day matching the given gregorian
    year/day."""
    shire_day = gregorian_day + 9
    if isleap(gregorian_year) and shire_day > 366:
        shire_year = gregorian_year + 1
        shire_day %= 366
    elif not isleap(gregorian_year) and shire_day > 365:
        shire_year = gregorian_year + 1
        shire_day %= 365
    else:
        shire_year = gregorian_year

    return shire_year, shire_day
Exemplo n.º 24
0
	def days_between_nl(self, d1,d2):
		"""" This function removes the leap days"""
		if calendar.isleap(d1.year) or calendar.isleap(d2.year):
			if calendar.isleap(d1.year):
				leapDate = datetime.datetime(year=d1.year, month=2, day=29)
			elif calendar.isleap(d2.year):
				leapDate = datetime.datetime(year=d2.year, month=2, day=29)
			if d1 <= leapDate <= d2:
				days_between =(d2-d1).days * 1.0 -1
			else:
				days_between =(d2-d1).days *1.0
		else:
			days_between = (d2-d1).days * 1.0
		return days_between
def calendar():

	import calendar#引入calender

	#获取某月日历
	cal=calendar.month(2017,1)
	print '以下输出2017年1月的日历 '
	print cal

	#判断是否为闰年
	print calendar.isleap(2016)
	print calendar.isleap(2017)

	#获取某年日历
	print calendar.calendar(2017,w=2,l=1,c=6)
Exemplo n.º 26
0
def get_bom_grid(var, yyyymmdd, month):
    """
    Given a variable VAR and date YYYYMMDD, fetch the .grid file from 
    the Bureau server using wget. If MONTH != 0, monthly files are fetched
    rather than daily.  Return the name of the file fetched.
    """

    monthday = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
    interval = 'day' if month == 0  else 'month'
    key = var+'/'+interval
    if key not in vars:
        raise ValueError("No such var ("+var+")")

    try:
        s = datetime.strptime(yyyymmdd, "%Y%m%d") 
    except ValueError:
        raise ValueError("Invalid date ("+yyyymmdd+")")

    if month:
        if s.month == 2 and calendar.isleap(s.year): monthday[2] = 29
        fname = "%04d%02d01%04d%02d%02d.grid.Z" % (s.year, s.month, s.year, s.month, monthday[s.month-1])
    else:
        fname = yyyymmdd+yyyymmdd+".grid.Z"
    out = filePrefix[key]+'_'+fname

    if os.path.exists(out): 
        raise RuntimeError("File already exists ("+out+")")

    url = vars[key]+"/"+fname
    if subprocess.call([WGET, '--output-document='+out, url]): 
        os.remove(out)
        raise IOError("Calling %s --output-document=%s %s" % (WGET, out, url))
    return out
Exemplo n.º 27
0
def main(connection, line):
	seasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]
	days = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]
	seasonholidays = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"]
	apostleholidays = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay" ]
	today = date.today()
	is_leap_year = calendar.isleap(today.year)
	day_of_year = today.timetuple().tm_yday

	if is_leap_year and day_of_year >= 60:
		day_of_year -= 1

	season, day = divmod(day_of_year, 73)

	dayindex = (day_of_year - 1) % 5
	season = season % 4
	year = today.year + 1166
	if is_leap_year and today.month == 2 and today.day == 29:
		ddate = "Today is St. Tib's Day, YOLD %d" % year
	elif today.month == 3 and today.day == 25:
		ddate = "Today is %s, the %s day of %s in the YOLD %d. Don't Panic! Celebrate: Towel Day!" % (days[dayindex], DayNum(day), seasons[season], year)
	elif day == 5:
		ddate = "Today is %s, the %s day of %s in the YOLD %d. Celebrate: %s!" % (days[dayindex], DayNum(day), seasons[season], year, apostleholidays[season])
	elif day == 50:
		ddate = "Today is %s, the %s day of %s in the YOLD %d. Celebrate: %s!" % (days[dayindex], DayNum(day), seasons[season], year, seasonholidays[season])
	else:
		ddate = "Today is %s, the %s day of %s in the YOLD %d." % (days[dayindex], DayNum(day), seasons[season], year)
	Channel.send(ddate)
Exemplo n.º 28
0
	def YearDayIntersect(self,ydrulelist):
		
		rlist = []
		
		if calendar.isleap(self.starttime.year):
			MMASK[1] = 29
		else:
			MMASK[1] = 28
		
		for yearday in ydrulelist:
			
			if (MMASK[1] == 29 and yearday > 366) or \
			   (MMASK[1] == 28 and yearday > 365):
				continue
			
			m = 0
			ydc = yearday
			while True:
				yc = ydc - MMASK[m]
				if yc <= 0:
					break
				ydc = yc
				m+=1
	
			isect=self.Intersect(TSFromStartAndDelta(datetime.datetime(self.starttime.year,m+1,ydc,0,0,0),datetime.timedelta(days=1)))
			
			if isect != None:
				rlist.append(isect)
				
		return rlist
Exemplo n.º 29
0
 def wrapper(*args, **kw):
     args_list = list(args)
     year = int(args_list[0][0:4]) 
     if calendar.isleap(year):
         args_list[0] = str(year + 1) + args_list[0][4:]
         ret = func(*args_list, **kw)
     return str(int(ret[0:4]) - 1) + ret[4:]
Exemplo n.º 30
0
def is_leap(n):
    # Eerst implementatiemogelijkheid
    #
    # if (year % 4) != 0:
    #     return False
    # else:
    #     if (year % 100) != 0:
    #         return True
    #     else:
    #         if (year % 400) != 0:
    #             return False
    #         else:
    #             return True
    #
    # Tweede implementatiemogelijkheid
    # if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
    #   return True

    # Derde implementatiemogelijkheid
    # if n % 400 == 0:
    #     return True
    # if n % 100 == 0:
    #     return False
    # if n % 4 == 0:
    #     return True
    # else:
    #     return False

    return calendar.isleap(n)
Exemplo n.º 31
0
# if n%2 != 0:
#     print("ODD")
#     print("N is odd")
# else:
#      print("Even")


# for i in range(0,n):
#     print(i**2)

# if __name__ == '__main__':
#     n = int(input())


def is_leap(year):
    # leap = False
    # if (year%4 ==0 and year %100 ==0 and year % 400 ==0):
    #     leap = True
    return year % 4 == 0 and (year % 100 != 0 and year % 400 == 0)


year = int(input())
if is_leap(year):
    print("is_leap(year)")
else:
    print("isNot_leap(year)")

import calendar

print(calendar.isleap(int(input("Enter Year"))))
Exemplo n.º 32
0
__author__ = 'prasadmodi'
import calendar
year = int(input("Enter Year to check if Leap or Not: "))
print(calendar.isleap(year))

Exemplo n.º 33
0
    def fromdelta(cls, delta, adjust_timezone=False):
        """
        Creates an XSD dateTime/date instance from a datetime.timedelta related to
        0001-01-01T00:00:00 CE. In case of a date the time part is not counted.

        :param delta: a datetime.timedelta instance.
        :param adjust_timezone: if `True` adjust the timezone of Date objects \
        with eventually present hours and minutes.
        """
        try:
            dt = datetime.datetime(1, 1, 1) + delta
        except OverflowError:
            days = delta.days
            if days > 0:
                y400, days = divmod(days, DAYS_IN_400Y)
                y100, days = divmod(days, DAYS_IN_100Y)
                y4, days = divmod(days, DAYS_IN_4Y)
                y1, days = divmod(days, 365)
                year = y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1
                if y1 == 4 or y100 == 4:
                    year -= 1
                    days = 365

                td = datetime.timedelta(days=days,
                                        seconds=delta.seconds,
                                        microseconds=delta.microseconds)
                dt = datetime.datetime(4 if isleap(year) else 6, 1, 1) + td

            elif days >= -366:
                year = -1
                td = datetime.timedelta(days=days,
                                        seconds=delta.seconds,
                                        microseconds=delta.microseconds)
                dt = datetime.datetime(5, 1, 1) + td

            else:
                days = -days - 366
                y400, days = divmod(days, DAYS_IN_400Y)
                y100, days = divmod(days, DAYS_IN_100Y)
                y4, days = divmod(days, DAYS_IN_4Y)
                y1, days = divmod(days, 365)
                year = -y400 * 400 - y100 * 100 - y4 * 4 - y1 - 2
                if y1 == 4 or y100 == 4:
                    year += 1
                    days = 365

                td = datetime.timedelta(days=-days,
                                        seconds=delta.seconds,
                                        microseconds=delta.microseconds)
                if not td:
                    dt = datetime.datetime(4 if isleap(year + 1) else 6, 1, 1)
                    year += 1
                else:
                    dt = datetime.datetime(5 if isleap(year + 1) else 7, 1,
                                           1) + td
        else:
            year = dt.year

        if issubclass(cls, Date10):
            if adjust_timezone and dt.hour or dt.minute:
                if dt.tzinfo is None:
                    hour, minute = dt.hour, dt.minute
                else:
                    hour = dt.hour - dt.tzinfo.offset.hours
                    minute = dt.minute - dt.tzinfo.offset.minutes

                if hour < 14 or hour == 14 and minute == 0:
                    tz = Timezone(
                        datetime.timedelta(hours=-hour, minutes=-minute))
                    dt = dt.replace(tzinfo=tz)
                else:
                    tz = Timezone(
                        datetime.timedelta(hours=-dt.hour + 24,
                                           minutes=-minute))
                    dt = dt.replace(tzinfo=tz)
                    dt += datetime.timedelta(days=1)

            return cls(year, dt.month, dt.day, tzinfo=dt.tzinfo)
        return cls(year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
                   dt.microsecond, dt.tzinfo)
Exemplo n.º 34
0
def most_frequent_days(year):
    days = (weekday(year, 1, i + 1) for i in range(1 + isleap(year)))
    return [day_name[d] for d in sorted(days)]
Exemplo n.º 35
0
# File Name...........: hw8_임정
# Program Description.: 함수를 정의하고 활용하는 법을 익힌다.
#                       Package 와 Module 을 활용하는 법을 익힌다.

import datetime  # datetime 모듈 불러오기
import calendar  # calendar 모듈 불러오기
import collections  # collections 모듈 불러오기

# datetime 모듈을 불러와 현재 시간을 출력해본다.
now = datetime.datetime.now()  # datetime.now 함수를 이용해 now 변수에 할당
current = datetime.datetime.strftime(
    now, '%Y-%m-%d %H:%M:%S')  # strftime 함수로 년-월-일 시:분:초 를 할당
print(current)  # 시간을 출력

# calendar 모듈을 불러와 현재 시간을 출력해 본다
print(calendar.isleap(2050))  # 2050년이 윤년인지여부를 출력
day = calendar.weekday(2050, 7, 7)  # 2050년이 7월 7일이 무슨 요일인지 day 변수에 할당
print(day)  # day 변수를 출력한다.


# 문장 내 모음 개수를 세고 가장 많은 개수를 모음을 대문자로 만든다.
def vowel(s):  # vowel 함수를 정의, 하나의 전달인자
    cnt = collections.Counter(s)  # 전달받은 값을 Counter 함수를 이용해  cnt 에 할당
    print(cnt)
    vowels = {
        'a': 0,
        'e': 0,
        'i': 0,
        'o': 0,
        'u': 0
    }  # vowels dict 에 모음을 key 로 갯수를 value 로 저장
Exemplo n.º 36
0
 def L(self):
     "Boolean for whether it is a leap year; i.e. True or False"
     return calendar.isleap(self.data.year)
Exemplo n.º 37
0
    def _draw_year(self, dr: svgwrite.Drawing, size: XY, offset: XY, year: int):
        min_size = min(size.x, size.y)
        outer_radius = 0.5 * min_size - 6
        radius_range = ValueRange.from_pair(outer_radius / 4, outer_radius)
        center = offset + 0.5 * size

        if self._rings:
            self._draw_rings(dr, center, radius_range)

        year_style = f"dominant-baseline: central; font-size:{min_size * 4.0 / 80.0}px; font-family:Arial;"
        month_style = f"font-size:{min_size * 3.0 / 80.0}px; font-family:Arial;"

        dr.add(
            dr.text(
                f"{year}",
                insert=center.tuple(),
                fill=self.poster.colors["text"],
                text_anchor="middle",
                alignment_baseline="middle",
                style=year_style,
            )
        )
        df = 360.0 / (366 if calendar.isleap(year) else 365)
        day = 0
        date = datetime.date(year, 1, 1)
        while date.year == year:
            text_date = date.strftime("%Y-%m-%d")
            a1 = math.radians(day * df)
            a2 = math.radians((day + 1) * df)
            if date.day == 1:
                (_, last_day) = calendar.monthrange(date.year, date.month)
                a3 = math.radians((day + last_day - 1) * df)
                sin_a1, cos_a1 = math.sin(a1), math.cos(a1)
                sin_a3, cos_a3 = math.sin(a3), math.cos(a3)
                r1 = outer_radius + 1
                r2 = outer_radius + 6
                r3 = outer_radius + 2
                dr.add(
                    dr.line(
                        start=(center + r1 * XY(sin_a1, -cos_a1)).tuple(),
                        end=(center + r2 * XY(sin_a1, -cos_a1)).tuple(),
                        stroke=self.poster.colors["text"],
                        stroke_width=0.3,
                    )
                )
                path = dr.path(
                    d=("M", center.x + r3 * sin_a1, center.y - r3 * cos_a1),
                    fill="none",
                    stroke="none",
                )
                path.push(
                    f"a{r3},{r3} 0 0,1 {r3 * (sin_a3 - sin_a1)},{r3 * (cos_a1 - cos_a3)}"
                )
                dr.add(path)
                tpath = svgwrite.text.TextPath(
                    path, date.strftime("%B"), startOffset=(0.5 * r3 * (a3 - a1))
                )
                text = dr.text(
                    "",
                    fill=self.poster.colors["text"],
                    text_anchor="middle",
                    style=month_style,
                )
                text.add(tpath)
                dr.add(text)
            if text_date in self.poster.tracks_by_date:
                self._draw_circle_segment(
                    dr,
                    self.poster.tracks_by_date[text_date],
                    a1,
                    a2,
                    radius_range,
                    center,
                )

            day += 1
            date += datetime.timedelta(1)
Exemplo n.º 38
0
- 上述所有模块使用理论上都需要先导入,string是特例
'''

import calendar
# calendar 获取一年的日历字符串
# 参数 可以不加,有默认值
# w = 每个日期之间的间隔字符数
# l = 每周所占用的行数
# c = 每个月之间的间隔字符数

cal = calendar.calendar(2018)
print(type(cal))  # 是一个str类型
# print(cal)

# isleap:判断某一年是否是闰年
print(calendar.isleap(2000))

# leapdays:获取指定年份之间的闰年的个数
print(calendar.leapdays(2001, 2018))

# month()获取某个月的日历字符串形式
# 格式:calender.month(年,月)
# 返回值:月日历的字符串
m1 = calendar.month(2018, 3)
print(m1)

# monthrange() 获取一个月 是从周几开始以及这个月的天数
# 格式:calender.monthrange(year,month)
# 返回值:元组(周几开始,天数)
# 注意:周默认,0-6,表示周一到周天
t = calendar.monthrange(2018, 4)  # 2018年4月是周天开始,一共有30天
Exemplo n.º 39
0
import calendar  # 日历模块

calendar.setfirstweekday(calendar.SUNDAY)  # 设置每周起始日期码。周一到周日分别对应 0 ~ 6
print(calendar.firstweekday())  # 返回当前每周起始日期的设置。默认情况下,首次载入calendar模块时返回0,即星期一。

c = calendar.calendar(2020)  # 生成2020年的日历,并且以周日为其实日期码
print(c)  # 打印2019年日历

print(calendar.isleap(1900))  # True.闰年返回True,否则返回False
count = calendar.leapdays(1996, 2010)  # 获取1996年到2010年一共有多少个闰年
print(count)
print(calendar.month(2200, 3))  # 打印2019年3月的日历
Exemplo n.º 40
0
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
    """Return a 2-tuple consisting of a time struct and an int containing
    the number of microseconds based on the input string and the
    format string."""

    for index, arg in enumerate([data_string, format]):
        if not isinstance(arg, str):
            msg = "strptime() argument {} must be str, not {}"
            raise TypeError(msg.format(index, type(arg)))

    global _TimeRE_cache, _regex_cache
    with _cache_lock:
        locale_time = _TimeRE_cache.locale_time
        if (_getlang() != locale_time.lang or time.tzname != locale_time.tzname
                or time.daylight != locale_time.daylight):
            _TimeRE_cache = _TimeRE()
            _regex_cache.clear()
            locale_time = _TimeRE_cache.locale_time
        if len(_regex_cache) > _CACHE_MAX_SIZE:
            _regex_cache.clear()
        format_regex = _regex_cache.get(format)
        if not format_regex:
            try:
                format_regex = _TimeRE_cache.compile(format)
            # KeyError raised when a bad format is found; can be specified as
            # \\, in which case it was a stray % but with a space after it
            except KeyError as err:
                bad_directive = err.args[0]
                if bad_directive == "\\":
                    bad_directive = "%"
                del err
                raise ValueError("'%s' is a bad directive in format '%s'" %
                                 (bad_directive, format)) from None
            # IndexError only occurs when the format string is "%"
            except IndexError:
                raise ValueError("stray %% in format '%s'" % format) from None
            _regex_cache[format] = format_regex
    found = format_regex.match(data_string)
    if not found:
        raise ValueError("time data %r does not match format %r" %
                         (data_string, format))
    if len(data_string) != found.end():
        raise ValueError("unconverted data remains: %s" %
                         data_string[found.end():])

    year = None
    month = day = 1
    hour = minute = second = fraction = 0
    tz = -1
    tzoffset = None
    # Default to -1 to signify that values not known; not critical to have,
    # though
    week_of_year = -1
    week_of_year_start = -1
    # weekday and julian defaulted to None so as to signal need to calculate
    # values
    weekday = julian = None
    found_dict = found.groupdict()
    for group_key in found_dict.keys():
        # Directives not explicitly handled below:
        #   c, x, X
        #      handled by making out of other directives
        #   U, W
        #      worthless without day of the week
        if group_key == 'y':
            year = int(found_dict['y'])
            # Open Group specification for strptime() states that a %y
            # value in the range of [00, 68] is in the century 2000, while
            # [69,99] is in the century 1900
            if year <= 68:
                year += 2000
            else:
                year += 1900
        elif group_key == 'Y':
            year = int(found_dict['Y'])
        elif group_key == 'm':
            month = int(found_dict['m'])
        elif group_key == 'B':
            month = _FULLMONTHNAMES.index(found_dict['B'].lower())
        elif group_key == 'b':
            month = _MONTHNAMES.index(found_dict['b'].lower())
        elif group_key == 'd':
            day = int(found_dict['d'])
        elif group_key == 'H':
            hour = int(found_dict['H'])
        elif group_key == 'I':
            hour = int(found_dict['I'])
            ampm = found_dict.get('p', '').lower()
            # If there was no AM/PM indicator, we'll treat this like AM
            if ampm in ('', locale_time.am_pm[0]):
                # We're in AM so the hour is correct unless we're
                # looking at 12 midnight.
                # 12 midnight == 12 AM == hour 0
                if hour == 12:
                    hour = 0
            elif ampm == locale_time.am_pm[1]:
                # We're in PM so we need to add 12 to the hour unless
                # we're looking at 12 noon.
                # 12 noon == 12 PM == hour 12
                if hour != 12:
                    hour += 12
        elif group_key == 'M':
            minute = int(found_dict['M'])
        elif group_key == 'S':
            second = int(found_dict['S'])
        elif group_key == 'f':
            s = found_dict['f']
            # Pad to always return microseconds.
            s += "0" * (6 - len(s))
            fraction = int(s)
        elif group_key == 'A':
            weekday = locale_time.f_weekday.index(found_dict['A'].lower())
        elif group_key == 'a':
            weekday = locale_time.a_weekday.index(found_dict['a'].lower())
        elif group_key == 'w':
            weekday = int(found_dict['w'])
            if weekday == 0:
                weekday = 6
            else:
                weekday -= 1
        elif group_key == 'j':
            julian = int(found_dict['j'])
        elif group_key in ('U', 'W'):
            week_of_year = int(found_dict[group_key])
            if group_key == 'U':
                # U starts week on Sunday.
                week_of_year_start = 6
            else:
                # W starts week on Monday.
                week_of_year_start = 0
        elif group_key == 'z':
            z = found_dict['z']
            tzoffset = int(z[1:3]) * 60 + int(z[3:5])
            if z.startswith("-"):
                tzoffset = -tzoffset
        elif group_key == 'Z':
            # Since -1 is default value only need to worry about setting tz if
            # it can be something other than -1.
            found_zone = found_dict['Z'].lower()
            for value, tz_values in enumerate(locale_time.timezone):
                if found_zone in tz_values:
                    # Deal with bad locale setup where timezone names are the
                    # same and yet time.daylight is true; too ambiguous to
                    # be able to tell what timezone has daylight savings
                    if (time.tzname[0] == time.tzname[1] and time.daylight
                            and found_zone not in ("utc", "gmt")):
                        break
                    else:
                        tz = value
                        break

    if year is None:
        year = 1975
    if julian is None and week_of_year != -1 and weekday is not None:
        week_starts_Mon = True if week_of_year_start == 0 else False
        julian = _calc_julian_from_U_or_W(year, week_of_year, weekday,
                                          week_starts_Mon)
        if julian <= 0:
            year -= 1
            yday = 366 if calendar.isleap(year) else 365
            julian += yday
    # Cannot pre-calculate datetime_date() since can change in Julian
    # calculation and thus could have different value for the day of the week
    # calculation.
    if julian is None:
        # Need to add 1 to result since first day of the year is 1, not 0.
        julian = datetime_date(year, month, day).toordinal() - \
                 datetime_date(year, 1, 1).toordinal() + 1
    else:  # Assume that if they bothered to include Julian day it will
        # be accurate.
        datetime_result = datetime_date.fromordinal(
            (julian - 1) + datetime_date(year, 1, 1).toordinal())
        year = datetime_result.year
        month = datetime_result.month
        day = datetime_result.day
    if weekday is None:
        weekday = datetime_date(year, month, day).weekday()
    # Add timezone info
    tzname = found_dict.get("Z")
    if tzoffset is not None:
        gmtoff = tzoffset * 60
    else:
        gmtoff = None

    return (year, month, day, hour, minute, second, weekday, julian, tz,
            tzname, gmtoff), fraction
Exemplo n.º 41
0
def leapyear(year):
    return calendar.isleap(year)
Exemplo n.º 42
0
def _one_year_frac(start_date, end_date):
  year_length = 366.0 if calendar.isleap(start_date.year) else 365.0
  return (end_date - start_date).days / year_length
Exemplo n.º 43
0
t2 - t1

t = time.localtime()
t
type(t)
t[0]
t[6]

time.asctime(time.localtime(time.time()))
# for the above same we can use time.asctime()
# asctime is to get the time in readable format.
time.asctime()

time.timezone

time.tzname
#****************************************************************

import calendar
calendar.calendar(1250)

calendar.isleap(2016)
calendar.monthcalendar(2018, 8)
calendar.firstweekday()
t = calendar.weekday(2018, 8, 1)
t
if t == 0:
    print(' Monday')
elif t == 1:
    print('Tues day')
Exemplo n.º 44
0
# そうそう、こういう風に書きたかったんです。
#
# 場合によっては、Pandasモジュール(pandas.date_range)を使った方が便利かも知れません。
# 詳しくは参考資料#5を参照して下さい。

# ## 閏年(うるうどし)の判定
#
# calendarモジュールのisleap関数を使います。

# In[ ]:

import calendar

# In[ ]:

calendar.isleap(2016)

# In[ ]:

calendar.isleap(2015)

# In[ ]:

from datetime import date

# In[ ]:

d = date(2016, 7, 5)
calendar.isleap(d.year)

# ## datetimeモジュールに属するオブジェクトのbool評価
 def atmospheric_julian_day(year, month, day):
     if (calendar.isleap(year)):
         month_list = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]
     else:
         month_list = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
     return month_list[month-1] + day
Exemplo n.º 46
0
  if len(dateargs) != 2: raise ValueError('Specify begin-date and end-date, if no number of periods is given.')
  enddate = pandas.to_datetime(dateargs[1]) - offset
  datelist = pandas.date_range(begindate, enddate, freq=freq) # generate datelist

# open file, if not writing to stdout
if not lecho: stepfile = open(filename, mode='w')
# iterate over dates (skip first)
lastdate = datelist[0] + offset # first element
llastleap = False
for date in datelist[1:]:
  lcurrleap = False
  currentdate = date + offset
  # N.B.: offset is not the interval/frequency; it is an offset at the beginning of the month or week
  if lmonthly:
    mon = date.month +1 
    if mon == 2: maxdays = 29 if calendar.isleap(date.year) else 28  
    elif mon in [4, 6, 9, 11]: maxdays = 30
    else: maxdays = 31
    if currentdate > date + pandas.DateOffset(days=maxdays): 
      currentdate = date + pandas.DateOffset(days=maxdays)
  # handle calendars without leap days (turn Feb. 29th into Mar. 1st)
  if not lleap and calendar.isleap(currentdate.year) and ( currentdate.month==2 and currentdate.day==29 ):
    lcurrleap = True
    currentdate += pandas.DateOffset(days=1) # move one day ahead    
  # generate line for last step
#   print currentdate.month,currentdate.day
  if lleap or not (freq.lower()=='1d' and llastleap): 
    # skip if this is daily output, a leap day, and a non-leap-year calendar...
    stepline = "{0:s}   '{1:s}'  '{2:s}'\n".format(lastdate.strftime(stepform),lastdate.strftime(dateform),
                                                   currentdate.strftime(dateform))
    # write to appropriate output 
Exemplo n.º 47
0
     timeAx = {'table_entry': 'time1', 'units': time.units}
 elif key == 'SI3hrPt':
     timeAx = {'table_entry': 'time1', 'units': time.units}
 elif key == 'OmonC':
     # Create climatological time axis for the WOA13 (1955-2012) temporal range
     times = []
     times_bnds = []
     for count, months in enumerate(range(1, 13)):
         #print count,months
         if months in [1, 3, 5, 7, 8, 10, 12]:
             monthendday = 31
             hrs = 12
         elif months in [4, 6, 9, 11]:
             monthendday = 30
             hrs = 0
         elif isleap(int(1984)):
             monthendday = 29
             hrs = 12
         else:
             monthendday = 28
             hrs = 0
         times.append(
             cdt.componenttime(
                 1984, months, np.int(monthendday / 2.),
                 hrs).torel('days since 1955-1-1').value)
         # WOA13v2 extends from 1955 to 2012
         #                    times_bnds.append([cdt.componenttime(1955,months,1,0,0,0).torel('days since 1955-1-1'),
         #                                       cdt.componenttime(2012,months,monthendday,12,59,59).torel('days since 1955-1-1')])
         if months < 12:
             times_bnds.append([
                 cdt.componenttime(
Exemplo n.º 48
0
def read_daily_help_output(filename):
    """
    Read the daily output from .OUT HELP file and return the data as
    numpy arrays stored in a dictionary.
    """
    with open(filename, 'r') as csvfile:
        csvread = list(csv.reader(csvfile))

    nlay = None
    arr_years = []
    arr_days = []
    arr_rain = []
    arr_ru = []
    arr_et = []
    arr_ezone = []
    arr_headfirst = []
    arr_drainfirst = []
    arr_leakfirst = []
    arr_leaklast = []

    year = None
    nlay = nsub = None
    for i, line in enumerate(csvread):
        if line:
            line = line[0]
            if 'TOTAL NUMBER OF LAYERS' in line:
                nlay = int(line.split()[-1])
            elif 'TOTAL NUMBER OF SUBPROFILES' in line:
                nsub = int(line.split()[-1])
            if 'DAILY OUTPUT FOR YEAR' in line:
                year = int(line.split()[-1])
                days_in_year = 366 if calendar.isleap(year) else 365
            elif year is not None:
                try:
                    day = int(line[2:5])
                    rain = float(line[13:19])
                    ru = float(line[19:26])
                    et = float(line[26:33])
                    ezone = float(line[33:41])
                    headfirst = float(line[41:51])
                    drainfirst = float(line[51:61])
                    leakfirst = float(line[61:71])
                    leaklast = float(line[-10:])
                except ValueError:
                    pass
                else:
                    arr_years.append(year)
                    arr_days.append(day)
                    arr_rain.append(rain)
                    arr_ru.append(ru)
                    arr_et.append(et)
                    arr_ezone.append(ezone)
                    arr_headfirst.append(headfirst)
                    arr_drainfirst.append(drainfirst)
                    arr_leakfirst.append(leakfirst)
                    arr_leaklast.append(leaklast)
                    if day == days_in_year:
                        year = None

    dataf = {
        'years': np.array(arr_years).astype('uint16'),
        'days': np.array(arr_days).astype('uint16'),
        'rain': np.array(arr_rain).astype('float32'),
        'runoff': np.array(arr_ru).astype('float32'),
        'et': np.array(arr_et).astype('float32'),
        'ezone': np.array(arr_ezone).astype('float32'),
        'head first': np.array(arr_headfirst).astype('float32'),
        'drain first': np.array(arr_drainfirst).astype('float32'),
        'leak first': np.array(arr_leakfirst).astype('float32'),
        'leak last': np.array(arr_leaklast).astype('float32')
    }
    return dataf
Exemplo n.º 49
0
    def get_availability(self, year, month, day, bbox_text, requested_products,
                         patterns, client_availability):
        """ """
        insp = reflection.Inspector.from_engine(self.__engine)
        existing_tables = insp.get_table_names()
        products = [
            p for p in requested_products
            if (client_availability is not None and p in client_availability)
            or Storage.get_product_table_name(p) in existing_tables
        ]
        if 0 >= len(products):
            return None

        # Temporal filter
        if year is None:
            date_start = None
            date_stop = None
        elif month is None:
            date_start = datetime.date(year, 1, 1)
            days_extent = 365
            if calendar.isleap(year):
                days_extent += 1
            date_stop = date_start + datetime.timedelta(days=days_extent)
        elif day is None:
            date_start = datetime.date(year, month, 1)
            _, days_extent = calendar.monthrange(year, month)
            date_stop = date_start + datetime.timedelta(days=days_extent)
        else:
            date_start = datetime.date(year, month, day)
            date_stop = date_start + datetime.timedelta(days=1)

        # Spatial filter
        bbox_polygon = None
        if bbox_text is not None:
            west, south, east, north = bbox_text.split(',')
            bbox_polygon = 'POLYGON(({} {}, {} {}, {} {}, {} {}, {} {}))'
            bbox_polygon = bbox_polygon.format(west, north, east, north, east,
                                               south, west, south, west, north)

        result = {'years': {}, 'months': {}, 'days': {}}

        def update_availability(result, tkey, ttype, arity, product_index):
            """ """
            if tkey not in result[ttype]:
                result[ttype][tkey] = {
                    'datasets': arity,
                    'products': [product_index]
                }
            else:
                result[ttype][tkey]['datasets'] += arity
                if product_index not in result[ttype][tkey]['products']:
                    result[ttype][tkey]['products'].append(product_index)

        all_days = []
        product_index = 0
        for product_id in products:
            product_index = product_index + 1
            pattern = None
            if patterns is not None:
                pattern = patterns.get(product_id, None)
            if client_availability is not None:
                client_product_availability = client_availability.get(
                    product_id, [])
            else:
                client_product_availability = []
            product_availability = self.get_product_availability(
                product_id, date_start, date_stop, bbox_polygon, pattern)

            product_all_days = []
            for arity, start, stop in product_availability:
                while start <= stop:
                    product_all_days.append(
                        (start.year, start.month, start.day))
                    update_availability(result, start.year, 'years', arity,
                                        product_index)
                    if start.year == year:
                        update_availability(result, start.month, 'months',
                                            arity, product_index)
                        if start.month == month:
                            update_availability(result, start.day, 'days',
                                                arity, product_index)

                    start = start + datetime.timedelta(days=1)

            for arity, start in client_product_availability:
                product_all_days.append((start.year, start.month, start.day))
                update_availability(result, start.year, 'years', arity,
                                    product_index)
                if start.year == year:
                    update_availability(result, start.month, 'months', arity,
                                        product_index)
                    if start.month == month:
                        update_availability(result, start.day, 'days', arity,
                                            product_index)
            all_days.append(set(product_all_days))

        coloc_days = set.intersection(*all_days)
        coloc_years = set([x[0] for x in coloc_days])
        coloc_months = set([x[1] for x in coloc_days if x[0] == year])

        for y in result['years']:
            if y in coloc_years:
                result['years'][y]['coloc'] = products
            else:
                result['years'][y]['coloc'] = []
        for m in result['months']:
            if m in coloc_months:
                result['months'][m]['coloc'] = products
            else:
                result['months'][m]['coloc'] = []

        return result
Exemplo n.º 50
0
import math
print(math.sqrt(((971*971)+(179*179))))            #2.1

n = int(input())
print(n // 10 % 10)                           #2.2

a=123
print(sum([int(i) for i in str(a)]))          #2.3




                                                               #task 3

import calendar
a=print(calendar.isleap(2020))
if a==True:
  print('yes')
else: print('no')  

import calendar
input('enter year')
if input(calendar.isleap())=True:
 print('leap year') 

                                                               #task4
print("enter width:")
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
if a + b > c and a + c > b and b + c > a:
Exemplo n.º 51
0
def main():
    if sys.argv[1:]:
        year = int(sys.argv[1])
    else:
        year = int(raw_input('In which year were you born? '))
    if 0 <= year < 100:
        print "I'll assume that by", year,
        year = year + 1900
        print 'you mean', year, 'and not the early Christian era'
    elif not (1850 <= year <= time.localtime()[0]):
        print "It's hard to believe you were born in", year
        return

    if sys.argv[2:]:
        month = int(sys.argv[2])
    else:
        month = int(raw_input('And in which month? (1-12) '))
    if not (1 <= month <= 12):
        print 'There is no month numbered', month
        return

    if sys.argv[3:]:
        day = int(sys.argv[3])
    else:
        day = int(raw_input('And on what day of that month? (1-31) '))
    if month == 2 and calendar.isleap(year):
        maxday = 29
    else:
        maxday = calendar.mdays[month]
    if not (1 <= day <= maxday):
        print 'There are no', day, 'days in that month!'
        return

    bdaytuple = (year, month, day)
    bdaydate = mkdate(bdaytuple)
    print 'You were born on', format(bdaytuple)

    todaytuple = time.localtime()[:3]
    todaydate = mkdate(todaytuple)
    print 'Today is', format(todaytuple)

    if bdaytuple > todaytuple:
        print 'You are a time traveler.  Go back to the future!'
        return

    if bdaytuple == todaytuple:
        print 'You were born today.  Have a nice life!'
        return

    days = todaydate - bdaydate
    print 'You have lived', days, 'days'

    age = 0
    for y in range(year, todaytuple[0] + 1):
        if bdaytuple < (y, month, day) <= todaytuple:
            age = age + 1

    print 'You are', age, 'years old'

    if todaytuple[1:] == bdaytuple[1:]:
        print 'Congratulations!  Today is your', nth(age), 'birthday'
        print 'Yesterday was your',
    else:
        print 'Today is your',
    print nth(days - age), 'unbirthday'
Exemplo n.º 52
0
def recalculate_all_scores():
    historical_thresholds = {}

    # raleigh_thresholds.csv comes from Mathematica; generation process is currently manual
    with open('data/raleigh_thresholds.csv') as csv_file:
        reader = csv.reader(csv_file)
        for row in reader:
            historical_thresholds[int(row[0])] = float(row[1])

    # For now, empty collection and recalculate all scorings (since fields are changing frequently)
    db.scorings.remove()

    mongo_records = db.forecasts.find().sort("currently.time", DESCENDING)

    for mongo_record in mongo_records:
        scoring = {}
        report_time = arrow_dt.get(mongo_record["currently"]["time"]).to(
            mongo_record["timezone"])
        tomorrow = report_time.replace(days=+1).date()
        day_ordinal = int(tomorrow.strftime("%j"))

        # Pretend that leap years don't happen, since we don't have enough historical weather data to account for them
        if calendar.isleap(int(tomorrow.strftime("%Y"))) and day_ordinal >= 60:
            day_ordinal -= 1

        (score, hourly_scores) = thresholds.process_day(
            etl.forecast_io_to_qclcd(mongo_record))

        scoring['scored_date_iso'] = report_time.replace(
            days=+1).format("YYYY-MM-DD")
        # Recording the scored date as an ISO string has a use in processing.
        # If we were to only record a timestamp, that means an extra line of code to convert back to local timezone
        # before we can confidently check the date. (Even if we stored at UTC noon, there are UTC+12 and UTC-12 offsets
        # in the real world (UTC+14, even), so sometimes we'd get the wrong date if we didn't account for local offset.)

        scoring['origin_forecast_id'] = mongo_record["_id"]
        scoring['scored_date_friendly'] = report_time.replace(
            days=+1).format("MMMM D, YYYY")
        scoring['generated_datetime_arrow'] = pickle.dumps(
            arrow_dt.now().floor('second').to(mongo_record["timezone"]))
        scoring['report_datetime_arrow'] = pickle.dumps(report_time)
        scoring['report_datetime_native'] = datetime.datetime.utcfromtimestamp(
            mongo_record["currently"]["time"])
        scoring['eligible'] = True if isinstance(score, list) else False
        scoring['historical_threshold'] = historical_thresholds[day_ordinal]
        scoring['hourly_scores_diagnostic'] = hourly_scores
        if scoring['eligible']:
            scoring['qualifying_runs'] = [{
                'start': s.start,
                'end': s.end,
                'qualifying_score': s.worst_score
            } for s in score]
            scoring['qualifying_score'] = score[
                0].worst_score  # All qualifying runs will be tied in score
        else:
            scoring['ineligible_reason'] = score
        scoring['beat_threshold'] = True if (
            scoring['eligible']
            and scoring['qualifying_score'] < scoring['historical_threshold']
        ) else False

        db.scorings.insert_one(scoring)
print(datetime.date.today().isocalendar()[1])
print('current weekday of the week:')
print(datetime.date.today().isoweekday())    # MON is 1
print('current day of year:')
print(datetime.date.today().strftime('%j'))
print('current day of month:')
print(datetime.date.today().strftime('%d'))
print('current day of week:')
print(datetime.date.today().strftime('%A'))

"""
2. Write a Python program to determine whether a given year is a leap year.
"""
import calendar

print(calendar.isleap(2018))

"""
3. Write a Python program to convert a string to datetime.
Sample String : Jan 1 2014 2:43PM 
Expected Output : 2014-01-01 14:43:00
"""
import datetime

day = 'Jan 1 2014 2:43PM'
print(datetime.datetime.strptime(day, '%b %d %Y %I:%M%p'))

"""
4. Write a Python program to get the current time in Python. 
Sample Format :  13:19:49.078205
"""
Exemplo n.º 54
0
# coding:utf-8

import calendar
from datetime import *
import time

# 获取某个月的日历,返回字符串类型
cal = calendar.month(2015, 12)
print(cal)
calendar.setfirstweekday(calendar.SUNDAY)  # 设置日历的第一天
cal = calendar.month(2015, 12)
print(cal)

# 获取一年的日历
cal = calendar.calendar(2017)
print(cal)
cal = calendar.HTMLCalendar(calendar.MONDAY)
print(cal.formatmonth(2015, 12))
# 判断是否闰年、两个年份之间闰年的个数
print(calendar.isleap(2012))
print(calendar.leapdays(2010, 2015))
Exemplo n.º 55
0
import calendar

print(calendar.isleap(2016))
import calendar
print(calendar.isleap(1900))
print(calendar.isleap(2000))
print(calendar.isleap(2001))
import calendar as cal

c = cal.TextCalendar(cal.SUNDAY)
print(c.formatmonth(2019, 9))

import calendar as cal

c = cal.HTMLCalendar(cal.SUNDAY)
print(c.formatmonth(2019, 9))

for name in cal.month_name:
    print(name)

for name in cal.day_name:
    print(name)

print(cal.calendar(2012))

cal.isleap(2018)
Exemplo n.º 58
0
 def __add__(self, other):
     if isinstance(other, relativedelta):
         return self.__class__(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 if other.year is not None
                                    else self.year),
                              month=(other.month if other.month is not None
                                     else self.month),
                              day=(other.day if other.day is not None
                                   else self.day),
                              weekday=(other.weekday if other.weekday is not None
                                       else self.weekday),
                              hour=(other.hour if other.hour is not None
                                    else self.hour),
                              minute=(other.minute if other.minute is not None
                                      else self.minute),
                              second=(other.second if other.second is not None
                                      else self.second),
                              microsecond=(other.microsecond if other.microsecond
                                           is not None else
                                           self.microsecond))
     if isinstance(other, datetime.timedelta):
         return self.__class__(years=self.years,
                               months=self.months,
                               days=self.days + other.days,
                               hours=self.hours,
                               minutes=self.minutes,
                               seconds=self.seconds + other.seconds,
                               microseconds=self.microseconds + other.microseconds,
                               leapdays=self.leapdays,
                               year=self.year,
                               month=self.month,
                               day=self.day,
                               weekday=self.weekday,
                               hour=self.hour,
                               minute=self.minute,
                               second=self.second,
                               microsecond=self.microsecond)
     if not isinstance(other, datetime.date):
         return NotImplemented
     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
Exemplo n.º 59
0
def YEARFRAC(start_date, end_date, basis=0):
  """
  Calculates the fraction of the year represented by the number of whole days between two dates.

  Basis is the type of day count basis to use.

    * `0` (default) - US (NASD) 30/360
    * `1`   - Actual/actual
    * `2`   - Actual/360
    * `3`   - Actual/365
    * `4`   - European 30/360
    * `-1`  - Actual/actual (Google Sheets variation)

  This function is useful for financial calculations. For compatibility with Excel, it defaults to
  using the NASD standard calendar. For use in non-financial settings, option `-1` is
  likely the best choice.

  See <https://en.wikipedia.org/wiki/360-day_calendar> for explanation of
  the US 30/360 and European 30/360 methods. See <http://www.dwheeler.com/yearfrac/> for analysis of
  Excel's particular implementation.

  Basis `-1` is similar to `1`, but differs from Excel when dates span both leap and non-leap years.
  It matches the calculation in Google Sheets, counting the days in each year as a fraction of
  that year's length.

  Fraction of the year between 1/1/2012 and 7/30/12, omitting the Basis argument.
  >>> "%.8f" % YEARFRAC(DATE(2012, 1, 1), DATE(2012, 7, 30))
  '0.58055556'

  Fraction between same dates, using the Actual/Actual basis argument. Because 2012 is a Leap
  year, it has a 366 day basis.
  >>> "%.8f" % YEARFRAC(DATE(2012, 1, 1), DATE(2012, 7, 30), 1)
  '0.57650273'

  Fraction between same dates, using the Actual/365 basis argument. Uses a 365 day basis.
  >>> "%.8f" % YEARFRAC(DATE(2012, 1, 1), DATE(2012, 7, 30), 3)
  '0.57808219'

  More tests:
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30)), 10)
  0.4972222222
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30), 0), 10)
  0.4972222222
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30), 1), 10)
  0.4945355191
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30), 2), 10)
  0.5027777778
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30), 3), 10)
  0.495890411
  >>> round(YEARFRAC(DATE(2012, 1, 1), DATE(2012, 6, 30), 4), 10)
  0.4972222222
  >>> [YEARFRAC(DATE(2012, 1, 1), DATE(2012, 1, 1), t) for t in [0, 1, -1, 2, 3, 4]]
  [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
  >>> [round(YEARFRAC(DATE(1985, 3, 15), DATE(2016, 2, 29), t), 6) for t in [0, 1, -1, 2, 3, 4]]
  [30.955556, 30.959617, 30.961202, 31.411111, 30.980822, 30.955556]
  >>> [round(YEARFRAC(DATE(2001, 2, 28), DATE(2016, 3, 31), t), 6) for t in [0, 1, -1, 2, 3, 4]]
  [15.086111, 15.085558, 15.086998, 15.305556, 15.09589, 15.088889]
  >>> [round(YEARFRAC(DATE(1968, 4, 7), DATE(2011, 2, 14), t), 6) for t in [0, 1, -1, 2, 3, 4]]
  [42.852778, 42.855578, 42.855521, 43.480556, 42.884932, 42.852778]

  Here we test "basis 1" on leap and non-leap years.
  >>> [round(YEARFRAC(DATE(2015, 1, 1), DATE(2015, 3, 1), t), 6) for t in [1, -1]]
  [0.161644, 0.161644]
  >>> [round(YEARFRAC(DATE(2016, 1, 1), DATE(2016, 3, 1), t), 6) for t in [1, -1]]
  [0.163934, 0.163934]
  >>> [round(YEARFRAC(DATE(2015, 1, 1), DATE(2016, 1, 1), t), 6) for t in [1, -1]]
  [1.0, 1.0]
  >>> [round(YEARFRAC(DATE(2016, 1, 1), DATE(2017, 1, 1), t), 6) for t in [1, -1]]
  [1.0, 1.0]
  >>> [round(YEARFRAC(DATE(2016, 2, 29), DATE(2017, 1, 1), t), 6) for t in [1, -1]]
  [0.838798, 0.838798]
  >>> [round(YEARFRAC(DATE(2014, 12, 15), DATE(2015, 3, 15), t), 6) for t in [1, -1]]
  [0.246575, 0.246575]

  For these examples, Google Sheets differs from Excel, and we match Excel here.
  >>> [round(YEARFRAC(DATE(2015, 12, 15), DATE(2016, 3, 15), t), 6) for t in [1, -1]]
  [0.248634, 0.248761]
  >>> [round(YEARFRAC(DATE(2015, 1, 1), DATE(2016, 2, 29), t), 6) for t in [1, -1]]
  [1.160055, 1.161202]
  >>> [round(YEARFRAC(DATE(2015, 1, 1), DATE(2016, 2, 28), t), 6) for t in [1, -1]]
  [1.157319, 1.15847]
  >>> [round(YEARFRAC(DATE(2015, 3, 1), DATE(2016, 2, 29), t), 6) for t in [1, -1]]
  [0.997268, 0.999558]
  >>> [round(YEARFRAC(DATE(2015, 3, 1), DATE(2016, 2, 28), t), 6) for t in [1, -1]]
  [0.99726, 0.996826]
  >>> [round(YEARFRAC(DATE(2016, 3, 1), DATE(2017, 1, 1), t), 6) for t in [1, -1]]
  [0.838356, 0.836066]
  >>> [round(YEARFRAC(DATE(2015, 1, 1), DATE(2017, 1, 1), t), 6) for t in [1, -1]]
  [2.000912, 2.0]
  """
  # pylint: disable=too-many-return-statements
  # This function is actually completely crazy. The rules are strange too. We'll follow the logic
  # in http://www.dwheeler.com/yearfrac/excel-ooxml-yearfrac.pdf
  if start_date == end_date:
    return 0.0
  if start_date > end_date:
    start_date, end_date = end_date, start_date

  d1, m1, y1 = start_date.day, start_date.month, start_date.year
  d2, m2, y2 = end_date.day, end_date.month, end_date.year

  if basis == 0:
    if d1 == 31:
      d1 = 30
    if d1 == 30 and d2 == 31:
      d2 = 30
    if _last_of_feb(start_date):
      d1 = 30
      if _last_of_feb(end_date):
        d2 = 30
    return (_date_360(y2, m2, d2) - _date_360(y1, m1, d1)) / 360.0

  elif basis == 1:
    # This implements Excel's convoluted logic.
    if (y1 + 1, m1, d1) >= (y2, m2, d2):
      # Less than or equal to one year.
      if y1 == y2 and calendar.isleap(y1):
        year_length = 366.0
      elif (y1, m1, d1) < (y2, 2, 29) <= (y2, m2, d2) and calendar.isleap(y2):
        year_length = 366.0
      elif (y1, m1, d1) <= (y1, 2, 29) < (y2, m2, d2) and calendar.isleap(y1):
        year_length = 366.0
      else:
        year_length = 365.0
    else:
      year_length = (datetime.date(y2 + 1, 1, 1) - datetime.date(y1, 1, 1)).days / (y2 + 1.0 - y1)
    return (end_date - start_date).days / year_length

  elif basis == -1:
    # This is Google Sheets implementation. Call it an overkill, but I think it's more sensible.
    #
    # Excel's logic has the unfortunate property that YEARFRAC(a, b) + YEARFRAC(b, c) is not
    # always equal to YEARFRAC(a, c). Google Sheets implements a variation that does have this
    # property, counting the days in each year as a fraction of that year's length (as if each day
    # is counted as 1/365 or 1/366 depending on the year).
    #
    # The one redeeming quality of Excel's logic is that YEARFRAC for two days that differ by
    # exactly one year is 1.0 (not always true for GS). But in GS version, YEARFRAC between any
    # two Jan 1 is always a whole number (not always true in Excel).
    if y1 == y2:
      return _one_year_frac(start_date, end_date)
    return (
      + _one_year_frac(start_date, datetime.date(y1 + 1, 1, 1))
      + (y2 - y1 - 1)
      + _one_year_frac(datetime.date(y2, 1, 1), end_date)
    )

  elif basis == 2:
    return (end_date - start_date).days / 360.0

  elif basis == 3:
    return (end_date - start_date).days / 365.0

  elif basis == 4:
    if d1 == 31:
      d1 = 30
    if d2 == 31:
      d2 = 30
    return (_date_360(y2, m2, d2) - _date_360(y1, m1, d1)) / 360.0

  raise ValueError('Invalid basis argument %r' % (basis,))
Exemplo n.º 60
0
 def random_leap_year(self) -> int:
     hr_year = FAKE.random_int(min=-9999)
     while not isleap(hr_year + 78):  # convert to gregorian year
         hr_year = FAKE.random_int(min=-9999)
     return hr_year + 1