当前位置: 首页 > 工具软件 > leap-day > 使用案例 >

python中leap函数_Python calendar.isleap方法代碼示例

关志勇
2023-12-01

本文整理匯總了Python中calendar.isleap方法的典型用法代碼示例。如果您正苦於以下問題:Python calendar.isleap方法的具體用法?Python calendar.isleap怎麽用?Python calendar.isleap使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在模塊calendar的用法示例。

在下文中一共展示了calendar.isleap方法的23個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的Python代碼示例。

示例1: test_simple_model_with_annual_licence_multi_year

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:pywr,項目名稱:pywr,代碼行數:25,

示例2: getDOB

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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")

開發者ID:adipandas,項目名稱:python-gui-demos,代碼行數:26,

示例3: W

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:27,

示例4: W

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:26,

示例5: gregorian_valid

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:GenealogyCollective,項目名稱:gprime,代碼行數:18,

示例6: timegm

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:20,

示例7: coerce

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:proxysh,項目名稱:Safejumper-for-Desktop,代碼行數:23,

示例8: _calendar_month_middles

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:pvlib,項目名稱:pvlib-python,代碼行數:18,

示例9: _make_date_from_match

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:CERT-Polska,項目名稱:n6,代碼行數:23,

示例10: _get_fy_duration_factor

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:iw3hxn,項目名稱:LibrERP,代碼行數:24,

示例11: get_date_range_hours_from_year

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:architecture-building-systems,項目名稱:CityEnergyAnalyst,代碼行數:18,

示例12: to_jd

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

)

開發者ID:fitnr,項目名稱:convertdate,代碼行數:19,

示例13: legal_date

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:fitnr,項目名稱:convertdate,代碼行數:18,

示例14: dayname

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:fitnr,項目名稱:convertdate,代碼行數:19,

示例15: date_between

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:AvinashSingh786,項目名稱:Fraud-Analysis,代碼行數:19,

示例16: random_date

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:AvinashSingh786,項目名稱:Fraud-Analysis,代碼行數:18,

示例17: main

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:anomen-s,項目名稱:programming-challenges,代碼行數:21,

示例18: W

​點讚 6

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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

開發者ID:blackye,項目名稱:luscan-devel,代碼行數:27,

示例19: get_time

​點讚 5

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

def get_time():

"""

獲取時間

:return:

"""

# time.strftime("%F-%u-%j")

# F:年月日;u:星期幾;j:一年第幾天

# 時間數據

# [2019, 4, 18, 4, 108]

time_datas = [int(i) for i in time.strftime("%F-%u-%j").split('-')]

# 年

year = time_datas[0]

# 月

month = time_datas[1]

# 日

day = time_datas[2]

# 星期幾

week_d = week[time_datas[3]]

# 一年中的第幾天

time_d = time_datas[4]

# 判斷是否是閏年;閏年:366天,平年:365

if calendar.isleap(year):

percent = round(time_d * 100 / 366, 2)

else:

percent = round(time_d * 100 / 365, 2)

# time_content = '今天是:%d 年 %d 月 %d 日,星期%s\n報告主人!今年 %.2f%% 時間已流逝。' % (year, month, day, week_d, percent)

time_content = ('各位帥哥美女們,大家早上好!\n\n今天是:%d 年 %d 月 %d 日,星期%s~' % (year, month, day, week_d),

'\n\n報告主人!報告主人!報告主人!\n\n%d 年,歲月已陪伴主人走過:%.2f%%。' % (year, percent) + "餘下時光,請主人們溫柔以待哦!")

return time_content

# print(get_time())

開發者ID:xingag,項目名稱:tools_python,代碼行數:37,

示例20: value

​點讚 5

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

def value(self, timestep, scenario_index):

i = scenario_index.global_id

day_of_year = timestep.dayofyear

days_in_year = 365 + int(calendar.isleap(timestep.year))

if day_of_year == days_in_year:

return self._remaining[i]

else:

days_remaining = days_in_year - (day_of_year - 1)

return self._remaining[i] / days_remaining

開發者ID:pywr,項目名稱:pywr,代碼行數:11,

示例21: monthly_mean_daylight_hours

​點讚 5

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

def monthly_mean_daylight_hours(latitude, year=None):

"""

Calculate mean daylight hours for each month of the year for a given

latitude.

:param latitude: Latitude [radians]

:param year: Year for the daylight hours are required. The only effect of

*year* is to change the number of days in Feb to 29 if it is a leap

year. If left as the default, None, then a normal (non-leap) year is

assumed.

:return: Mean daily daylight hours of each month of a year [hours]

:rtype: List of floats.

"""

_check_latitude_rad(latitude)

if year is None or not calendar.isleap(year):

month_days = _MONTHDAYS

else:

month_days = _LEAP_MONTHDAYS

monthly_mean_dlh = []

doy = 1 # Day of the year

for mdays in month_days:

dlh = 0.0 # Cumulative daylight hours for the month

for daynum in range(1, mdays + 1):

sd = fao.sol_dec(doy)

sha = fao.sunset_hour_angle(latitude, sd)

dlh += fao.daylight_hours(sha)

doy += 1

# Calc mean daylight hours of the month

monthly_mean_dlh.append(dlh / mdays)

return monthly_mean_dlh

開發者ID:woodcrafty,項目名稱:PyETo,代碼行數:33,

示例22: L

​點讚 5

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

def L(self):

"Boolean for whether it is a leap year; i.e. True or False"

return calendar.isleap(self.data.year)

開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:5,

示例23: test_isleap

​點讚 5

# 需要導入模塊: import calendar [as 別名]

# 或者: from calendar import isleap [as 別名]

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)

開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:11,

注:本文中的calendar.isleap方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

 类似资料: