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
def check_year_range(self, start_date, years): if(start_date.month <= 2): ld = calendar.leapdays(start_date.year, start_date.year + years) else: # because we may catch the leap of the last year, # and i think this func is [start,end) ld = calendar.leapdays(start_date.year, start_date.year + years + 1) returns = factory.create_returns(365 * years + ld, self.trading_env08) metrics = risk.RiskReport(returns, self.trading_env) total_months = years * 12 self.check_metrics(metrics, total_months, start_date)
def _add_years(datetime, delta): sign = int(math.copysign(1, delta)) days = (abs(delta) * DAYS_IN_COMMON_YEAR + leapdays(*sorted((datetime.year, datetime.year + delta)))) * sign _check_overflow(datetime, days=delta) return datetime + dt.timedelta(days=days)
def _add_years(datetime, years): """Adds 'delta' of years to a 'datetime'.""" sign = int(math.copysign(1, years)) days = (abs(years) * DAYS_IN_COMMON_YEAR + leapdays(*sorted((datetime.year, datetime.year + years)))) * sign _check_overflow(datetime, days=years) return datetime + dt.timedelta(days=days)
def previous_leap_days(year): """Returns the number of leap years in the range [1, year).""" if year <= gregorian_reformation_year: return (year - 1) / ancient_leapyear_period # calendar.leapdays() calculates always according to the new method, # so in the "real world" it's off by 12 years/days when applicable return calendar.leapdays(1, year) + leapdays_function_error
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
def calculate_moon_position1(day,month,year,timeH,timeM,timeS): print "Calculated with set date: "+str(day)+"/"+str(month)+"/"+str(year)+"/ at " + str(timeH)+":"+str(timeM)+":"+str(timeS)+".\n" timeS+= 32.184 + leapseconds.dTAI_UTC_from_utc(datetime.datetime(year,month,day,timeH,timeM,timeS)).seconds time_as_frac_of_day = ((timeS/60.0 + timeM)/60.0 + timeH)/24.0 ## Step 1 - pg 144 ############## daystotal=0 for monthdays in daysinmonth[:month-1]: daystotal += monthdays daystotal += day ############ END ############## total_days = (year-1990)*365 + calendar.leapdays(1990, year+1) + \ ## Step 2 - pg 144 ############## + daystotal + time_as_frac_of_day ############ END ##############
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
def timegm(year, month, day, hour, minute, second): """Convert time tuple in GMT to seconds since epoch, GMT""" EPOCH = 1970 assert year >= EPOCH assert 1 <= month <= 12 days = 365*(year-EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days*24 + hour minutes = hours*60 + minute seconds = minutes*60 + second return seconds
def _perAgeChoiceSelector(self, params): """Choice selector for per age statistics. """ entity = params["entity"] birth_date = entity.birth_date today = params.get("today", date.today()) days = today - birth_date days -= timedelta(days=calendar.leapdays(birth_date.year, today.year)) if calendar.isleap(today.year) and today.timetuple()[7] > 31 + 29: days += timedelta(days=1) if calendar.isleap(birth_date.year) and birth_date.timetuple()[7] > 31 + 29: days += timedelta(days=1) return str(days.days / 365)
def timesince(d, now=None, reversed=False): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. 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. Adapted from http://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ # 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) if not now: now = datetime.datetime.now(utc if is_aware(d) else None) delta = (d - now) if reversed else (now - d) # Deal with leapyears by subtracing the number of leapdays delta -= datetime.timedelta(calendar.leapdays(d.year, now.year)) # 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(ugettext('0 minutes')) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = avoid_wrapping(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 += ugettext('') + avoid_wrapping(name2 % count2) return result
def timegm(year, month, day, hour, minute, second): """ Convert time tuple in GMT to seconds since epoch, GMT """ EPOCH = 1970 if year < EPOCH: raise ValueError("Years prior to %d not supported" % (EPOCH,)) assert 1 <= month <= 12 days = 365 * (year - EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days * 24 + hour minutes = hours * 60 + minute seconds = minutes * 60 + second return seconds
def timesince(dt=None, now=None): if dt is None: return 'N/A' if now is None: now = datetime.utcnow() delta = now - dt if delta.total_seconds() >= 0 and delta.total_seconds() < 60: return pgettext('timesince', 'just now') if delta.total_seconds() < 0 and delta.total_seconds() > -60: return pgettext('timesince', 'very soon') # Разбираемся с високосными днями leapdays = calendar.leapdays(dt.year, now.year) if leapdays != 0: if calendar.isleap(dt.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= timedelta(leapdays) since = abs(int(delta.total_seconds())) # Кусок первый result = '' # deal with pylint i = 0 seconds = 0 for i, (seconds, singular, plural) in enumerate(chunks): count = since // seconds if count != 0: result = npgettext('timesince', singular, plural, num=count) break # Кусок второй через запятую if i + 1 < len(chunks): seconds2, singular2, plural2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += pgettext('timesince', ', ') result += npgettext('timesince', singular2, plural2, num=count2) if delta.total_seconds() >= 0: return pgettext('timesince', '%(delta)s ago') % {'delta': result} return pgettext('timesince', 'in %(delta)s') % {'delta': result}
def time_ago(d, now=None): if not now: now = datetime.utcnow() try: d = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ") except ValueError: d = datetime.strptime(d, "%Y-%m-%dT%H:%M:%SZ") delta = now - d delta -= timedelta(calendar.leapdays(d.year, now.year)) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: return '0 minutes' for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break result = name % count if i + 1 < len(TIMESINCE_CHUNKS): seconds2, name2 = TIMESINCE_CHUNKS[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: result += ", " + name2 % count2 return result
def timegm(tmtuple): ''' returns epoch seconds from a GMT time tuple. ''' import calendar EPOCH = 1970 year, month, day, hour, minute, second = tmtuple[:6] if year < EPOCH: if year < 69: year = year + 2000 else: year = year + 1900 if year < EPOCH: raise ValueError, 'invalid year' if not 1 <= month <= 12: raise TypeError, 'invalid month' days = 365 * (year-EPOCH) + calendar.leapdays(EPOCH, year) for i in range(1, month): days = days + calendar.mdays[i] if month > 2 and calendar.isleap(year): days = days + 1 days = days + day - 1 hours = days * 24 + hour minutes = hours * 60 + minute seconds = minutes * 60 + second return seconds
def test_no_leapdays_upper_boundary(self): # test no leap years in range, when upper boundary is a leap year self.assertEqual(calendar.leapdays(2010, 2012), 0)
import calendar #importing modules for using in this program import datetime print(calendar.weekheader(2)) #prints day names print() print(calendar.month(2020,5,3)) #prints may 2020 with weekheadr 3 print() print(calendar.monthcalendar(2020,5)) #prints in matrix format print() print(calendar.calendar(2020)) ##whole yr day_of_week =calendar.weekday(2020,5,1) #prints day of the week print(day_of_week) is_leap=calendar.isleap(2020) print(is_leap) how_many_leap_days =calendar.leapdays(2000,2020) print(how_many_leap_days) date_time= datetime.datetime.now() #displays current date and time now print(date_time) print() #just a blank line date= datetime.date.today() #displays current date print(date)
def test_no_range(self): # test when no range i.e. two identical years as args self.assertEqual(calendar.leapdays(2010, 2010), 0)
def test_datetime(): """ 对test_datetime 模块的方法进行验证 :return: """ # 生成时间,和日期没有关系, # 不过需要传入对应的Hour、Minutes、seconds、microsecond # 可用于时间的比较 test_t = datetime.time(1, 2, 3, 4) print(test_t.minute) print(test_t.hour) print(test_t.second) print("*" * 20) # 生成简单型日期 test_dt = datetime.date.today() print(test_dt.weekday()) print(test_dt.month) print(test_dt.year) print(test_dt.day) # 从时间戳生成日期 print(datetime.date.fromtimestamp(time.time())) # 从现有时间创建 test_dt_1 = datetime.date(2019, 1, 6) print(test_dt_1.ctime()) # 获取当前的日期和时间 print("*" * 20) test_dt = datetime.datetime.today() print(test_dt) print(test_dt.time()) print(test_dt.date()) print(test_dt.now()) print(test_dt.ctime()) print(test_dt.weekday()) print(test_dt.year) print(test_dt.day) # 从时间戳加载时间 test_dt_stamp = datetime.datetime.fromtimestamp(time.time() - 10000) print(test_dt_stamp.now()) print(test_dt_stamp.year) print(test_dt_stamp.month) # 从格列高利历序号加载时间,其中公元 1 年 1 月 1 日的序号为 1 leap_num = calendar.leapdays(1, 2020) test_dt_dinal = datetime.datetime.fromordinal(736942 + leap_num) print(test_dt_dinal) # 时间的计算 print("*" * 20) test_today = datetime.datetime.today() print("today:", test_today) one_day = datetime.timedelta(days=1, hours=1, minutes=30) yesterday = test_today - one_day tomorrow = test_today + one_day print("yesterday:", yesterday) print("tomorrow:", tomorrow) # 也支持浮点数 one_point_five_day = one_day * 1.5 print(one_point_five_day) # 时间的比较 print("*" * 20) d1 = datetime.datetime.today() d2 = d1 + datetime.timedelta(days=1) if d1 < d2: print("lasted date:", d2) # 时间的格式化 today = datetime.datetime.today() today_format = today.strftime("%Y-%m-%d %H:%M:%S") print(today_format) # 将格式化的时间转成datetime today_d = datetime.datetime.strptime(today_format, "%Y-%m-%d %H:%M:%S") print(today_d)
calendar.prmonth(2020, 12) # 4.6.1.5 The calendar module import calendar print(calendar.weekday(2020, 12, 24)) print(calendar.weekday(2022, 1, 22)) # 4.6.1.6 The calendar module import calendar print(calendar.weekheader(3)) # 4.6.1.7 The calendar module import calendar print(calendar.isleap(2020)) print(calendar.leapdays(2010, 2021)) # Up to but not including 2021. # 4.6.1.9 The calendar module import calendar c = calendar.Calendar(calendar.SUNDAY) for weekday in c.iterweekdays(): print(weekday, end=" ") # 4.6.1.10 The calendar module import calendar c = calendar.Calendar()
print(u'第78行判断list是否是可迭代对象',isinstance([],Iterable)) print(u'第79行判断字典是否是可迭代对象',isinstance({"aa":123,"cc":123},Iterable)) #转换为Iterator对象 print('第87行Iterable转换为Iterator对象',isinstance(iter([x for x in range(10)]),Iterator)) #continue 语句跳出本次循环,而break跳出整个循环 for x in "HelloWorldhaha": if x=="r": continue print("now word:",x,) if x=="a": break #pass 用于保证代码的完整性,不做任何作用 for x in range(10): if x%3==0: pass print("NiHao",) print("num",x) #python的时间对象以一个元组的形式呈现分别为年,月,日,小时,分钟,秒一周第几天,一年第几天,是否夏令时 localtime = time.localtime(time.time()) print(localtime) #时间格式化 print(time.asctime(localtime)) print(calendar.month(2015,11)) print(calendar.leapdays(2000,2009))
import calendar # Python standard libraries list # https://docs.python.org/3/py-modindex.html # Documentation # https://docs.python.org/3/library/calendar.html # W stands for width, L stands for length print(calendar.month(2020, 11, w=10, l=0)) # Will print calendar for whole year C stands for distandce between two month and M for amount of month in on row print(calendar.calendar(2020, w=2, l=1, c=2, m=3)) print(calendar.weekday( 2020, 11, 30)) # Will print weekday number (MONDAY is 0 and SUNDAY is 6) print(calendar.isleap(2020)) # Will return True because 2020 is a leap year print( calendar.isleap(2018)) # Will return False because 2020 is not a leap year print(calendar.leapdays( 2000, 2020)) # Will return number of leap years between 2000 and 2020
print(calendar.month(2017, 9, w=5, l=2)) # wyswietlenie kalendarza na konkretny miesiac, na kazdy dzien # przeznaczone jest 5 znakow, a odstepy miedzy znakami wynosza 2 print("\n") print(calendar.month(2017, 9)) # wyswietlenie kalendarza bez dodatkowych parametrow print("\n") print("week day is", calendar.weekday(2017, 9, 29)) # ktory dzien tygodnia byl okreslonego dnia print("\n") calendar.setfirstweekday(6) # funkcja, ktora ustala ktory dzien tygodnia ma sie jako pierwszy wyswietlic, w tym # przypadku niedziela print(calendar.month(2017, 9)) print("\n") print("week day is", calendar.weekday(2017, 9, 29)) # nadal bedzie wyswietlany czwarty dzien print("\n") print("is 2020 a leap year", calendar.isleap(2020)) # sprawdza czy dany rok jest przystepny print("\n") print("Leap days 2000-2017", calendar.leapdays(2000, 2017)) # ile bylo dni przystepnych w tych latach, ale bez # roku 2017 print("Leap days 2000-2020", calendar.leapdays(2000, 2020)) # to samo ale bez roku 2020 print("Leap days 2000-2021", calendar.leapdays(2000, 2021)) # to samo ale 2020 juz sie liczy, ale bez 2021 print("\n") print(calendar.calendar(2018)) # parametrem jest rok, zwroci caly kalendarz na dany rok print("\n") # cwiczenie 1 print("Czas w postaci Unix Epoche", time.time()) print("Wersja dla człowieka", time.localtime(time.time())) print("\n")
print("Current time is... unix epoch", time.time()) print("\n") print("Current time is... tuple", time.localtime(time.time())) print("\n") print("Current time is... for human", time.asctime(time.localtime(time.time()))) print("\n") print("Current time is... for human", time.localtime(time.process_time())) import calendar print('---------------------------------------------') print(calendar.month(2017,9,w=5,l=2)) print('---------------------------------------------') print(calendar.month(2017,9)) print('---------------------------------------------') print('week day is',calendar.weekday(2017,9,29)) print('---------------------------------------------') calendar.setfirstweekday(6) print('---------------------------------------------') print(calendar.month(2017,9)) print('---------------------------------------------') print('week day is',calendar.weekday(2017,9,29)) print('---------------------------------------------') print('is 2020 a leap year?',calendar.isleap(2020)) print('---------------------------------------------') print('Leap days 2000-2017', calendar.leapdays(2000,2017)) print('Leap days 2000-2020', calendar.leapdays(2000,2020)) print('Leap days 2000-2021', calendar.leapdays(2000,2021)) print(calendar.calendar(2020))
# 3.3.0/py-modindex.html, and look at the documentation on the calendar # module. # b. Import the calendar module. import calendar # c. Using the help function, read the description of the function isleap. help(calendar.isleap) # d. Use isleap to determine the next leap year. from datetime import date year = date.today().year while not calendar.isleap(year): year += 1 print('Next leap year is:', year) # e. Use dir to get a list of what calendar contains. dir(calendar) # f. Find and use a function in the calendar module to determine how many # leap years there will be between the years 2000 and 2050, inclusive. start = 2000 finish = 2050 print('Number of leap years between', start, 'and', finish, 'is', calendar.leapdays(start, finish)) # g. Find and use a function in the calendar module to determine which day # of the week July 29, 2016, will be. print('29th July 2016 is a', calendar.day_name[calendar.weekday(2016, 7, 29)])
def min_age(): today = utc.now().date() leaps = leapdays((today.year-12), today.year) withoutleaps = 12 - leaps return today - timedelta(days=((withoutleaps*365)+(leaps*364)))
import calendar #输出日历 #l每行间隔字符数 #w每个日期间隔字符数 #c每个月间隔字符数 #m一行显几个月 a = calendar.calendar(2018,l=1,w=1,c=1) print(a) #isleap,判断闰年 bol = calendar.isleap(2018) print(bol) #leapdays,两个年份之间闰年个数 num = calendar.leapdays(2000,2018) print(num) #manth,月份日历 print(calendar.month(2018,9)) #monthrange,获取某个月第一天是周几,有几天,0代表周一 print(calendar.monthrange(2018,9)) #monthcalendar,返回一个月的矩阵列表list for i in calendar.monthcalendar(2018,9): print() for j in i: print(str(j).rjust(3," "),end=" ") #prcal 直接打印日历不需要print
print "Calculated with set date: "+str(day)+"/"+str(month)+"/"+str(year)+"/ at " + str(timeH)+":"+str(timeM)+":"+str(timeS)+".\n" ## Step 1 - pg 144 ############### timeS+= 32.184 + leapseconds.dTAI_UTC_from_utc(datetime.datetime(year,month,day,timeH,timeM,timeS)).seconds #converting to Terrestrial Dynamic Time time_as_frac_of_day = ((timeS/60.0 + timeM)/60.0 + timeH)/24.0 daystotal=0 for monthdays in daysinmonth[:month-1]: daystotal += monthdays daystotal += day #print "Step 1 - d =",daystotal + time_as_frac_of_day #################################### ## Step 2 - pg 144 ############### total_days = (year-1990)*365 + calendar.leapdays(1990, year+1) + daystotal + time_as_frac_of_day #print "Step 2 - D =",total_days #################################### ## Step 3 - pg 144 ############### ### Step 3 = pg 88 Mean_anomaly1 = (360/days_for_360 * total_days) Mean_anomaly1 = adjustrange1(Mean_anomaly1) ### ############## ### Step 4 = pg 88 Mean_anomaly2 = Mean_anomaly1 + Ecliptic_longitude - Ecliptic_longitude_of_perigee if Mean_anomaly2 < 0: Mean_anomaly2 += 360 #print "Step 3 - M =",Mean_anomaly2 ##still step 3 on pg144 ### ############## ### Step 5 = pg 88
import calendar calc = calendar.month(2016, 9) print(calc) print(type(calc)) print(calendar.isleap(2016)) print(calendar.leapdays(1995, 2017))
def timesince( d: Optional[datetime] = None, now: Optional[datetime] = None, reversed: bool = False, depth: int = 2, none_value: str = "Never", ) -> str: """ 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 `depth` 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. `depth` is an optional integer to control the number of adjacent time units returned. Adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ time_strings = TIME_STRINGS if not d: return none_value if depth <= 0: raise ValueError("depth must be greater than 0.") # Convert date to datetime for comparison. if not isinstance(d, datetime): d = datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime): now = datetime(now.year, now.month, now.day) now = now or datetime.now(timezone.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 -= 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 time_strings["minute"][0] % {"num": 0} for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break else: return time_strings["minute"][0] % {"num": 0} result = [] current_depth = 0 while i < len(TIMESINCE_CHUNKS) and current_depth < depth: seconds, name = TIMESINCE_CHUNKS[i] count = since // seconds if count == 0: break if count == 1: time_string = time_strings[name][0] % {"num": count} else: time_string = time_strings[name][1] % {"num": count} result.append(time_string) since -= seconds * count current_depth += 1 i += 1 return ", ".join(result)
# filename='C:/Users/meridian/Desktop/Test2.xlsx' # filename2='C:/Users/meridian/Desktop/新文件.xlsx' # # def replace_xls(sheetname): # wb=openpyxl.load_workbook(filename) # wb2=openpyxl.load_workbook(filename2) # # ws=wb[sheetname] # ws2=wb2[sheetname] # # #两个for循环遍历整个excel单元格的内容 # for i,row in enumerate(ws.iter_rows()): # for j,cell in enumerate(row): # ws2.cell(row=i+1,column=j+1,value=cell.value) # wb2.save(filename2) # replace_xls("Sheet1") import calendar #自带三个参数,调整各个数之间的间隔。 cal = calendar.calendar(2018) print(cal) #isleap:判断某一年是否闰年 calendar.isleap(2001) #leapdays:获取指定年份之间的闰年个数 calendar.leapdays(2001, 2011) import openpyxl excel = openpyxl.load_workbook()
fCurrent_time = time.asctime(present_time) #Formatted current time print(fCurrent_time) #Get calender of a month import calendar print(calendar.month(2016, 12)) # miscellaneous time methods print(time.clock()) #returns current CPU time as float points time.sleep(2) #suspends the thread for a specific time period print("Two seconds done!") # miscellaneous calendar methods print(calendar.isleap(2016)) #returns true or false print(calendar.leapdays(2012, 2016)) print(calendar.monthcalendar(2016, 5)) """ Other interesting modules are 1)The datetime Module 2)The pytz Module 3)The dateutil Module """ """ Functions : In python arguments are passed by reference There are 4 types of arrguments 1) Regular Arguments 2) Keyword Arguments 3) Default Arguments 4) Variable-length Arguments """ #Anonymous Function : You can use the lambda keyword to create small anonymous functions. sum = lambda arg1, arg2: arg1 + arg2 #Function is defined here
# Calenndar Module # First Weekday # Calendar.firstweekday() # Returns the current setting for the weekday that starts each week. # default is Monday i.e '0' import calendar print(calendar.firstweekday()) # Leap year # calendar.isleap(year) # returns true if the year is ;eap year, else false year = 2020 print("Is 2020 a leap year?", calendar.isleap(2020)) # Leap days # calendar leapdays(y1. y2) # Returns the total number of leap days within range [y1,y2] y1 = 2020 y2 = 2021 print("No. of leap days this year:", calendar.leapdays(y1, y2)) # Calendar of month # calendar.month(year,month,w,l) # Retruns multiline stirng of the calendar for Month # w is width of chars of each date, l is lines for each week year = 2020 month = 5 calendar.month(year, month, w=2, l=1)
import calendar print(calendar.weekheader(3)) print(calendar.firstweekday()) print(calendar.weekday(1971, 11, 25)) print(calendar.month(2020, 9, w=3)) print(calendar.monthcalendar(2020, 9)) print(calendar.calendar(2020)) day_of_the_week = calendar.weekday(2020, 9, 24) print(day_of_the_week) print(calendar.isleap(2020)) print(calendar.leapdays( 1971, 2021, ))
import math import calendar """Displays Tutorial 3 Exercises""" print("Int: " + str(abs(round(-4.3)))) print("Float: " + str(math.fabs(round(-4.3)))) print("Ceiling: " + str(math.ceil(math.sin(math.radians(34.5))))) print("Number of Leap years: " + str(calendar.leapdays(2000, 2050))) print("Day of the week: " + str(calendar.weekday(2019, 9, 13))) print("Capitalised \'boolean\': " + "boolean".capitalize()) print("First occurrence of \'2\' in \'C02 H20\': " + str("C02 H20".find("2"))) print("Last occurrence of \'2\' in \'C02 H20\': " + str("C02 H20".rfind("2"))) print("Second occurrence of \'2\' in \'C02 N02 H20\': " + str("C02 N02 H20".find("2", "C02 N02 H20".find("2") + 1))) print("Does \'Boolean\' begin with a lowercase: " + str("Boolean".startswith("B"))) print("MoNDaY to lowercase: " + "MoNDaY".lower().capitalize()) print("Remove leading whitespace from \' Monday\': " + " Monday".lstrip())
# html calendar os.system("cls") h = calendar.HTMLCalendar() print(h.formatmonth(2018, 12)) # formatmonth(theyear,themonth,withyear=True) print(h.formatyear(2018, 5)) # year width print(h.formatyearpage(2018, css=None) ) # formatyearpage(theyear,width=3,css=’calendar.css’,encoding=None) t.setfirstweekday(calendar.SUNDAY) print(t.formatyear(2018, 5)) print(t.firstweekday) print(calendar.isleap(2020)) print(calendar.leapdays(1990, 2020)) print(calendar.weekday(2018, 12, 31)) print(calendar.weekheader(1)) print(calendar.weekheader(2)) print(calendar.weekheader(3)) print(calendar.monthrange(2018, 12)) for i in calendar.monthcalendar(2018, 12): print(i) print(calendar.prmonth(2018, 12)) print(calendar.month(2018, 12)) print(calendar.prcal(2018)) print(calendar.calendar(2020))
import datetime print(calendar.calendar(2018, w=3, l=2, c=4)) ''' calendar.calendar(year,w,l,c) is return calendar. w=width of character l=no of line c=space ''' from calendar import monthrange print(calendar.isleap(2012)) ''' isleap year is used to check a year is leap year or not return True if leap year then else False ''' print("no of leapyears:", calendar.leapdays(2010, 2030)) ''' it is used to get no of leap years between range of year. ''' print(calendar.firstweekday()) ''' its used to give default day of week start with 0 monday ''' print(calendar.month(2018, 12, w=4, l=1)) ''' its used to get specific month calendar ''' print("start month day and total days", calendar.monthrange(2018, 12)) ''' its used to get day number of month and numbers of days in month ''' dt = '20/12/2018' day, month, year = (int(x) for x in dt.split('/')) ans = datetime.date(year, month, day) start_day = calendar.monthrange(year, month)
# 常量 print('datetime能标示的最小年份和最大年份是',datetime.MINYEAR,datetime.MAXYEAR) # 方法 print("本地当前时间是",datetime.datetime.today()) print("指定的时区当前时间是",datetime.datetime.now()) # 如果传入市区的参数就获取制定市区的当前时间,没有就是本地的 # utcnow() 返回一个当前utc时间的datetime对象 print("返回一个当前utc时间的datetime",datetime.datetime.utcnow()) # utc标准时间 # fromttimestamp(timestamp,[tz]) 传入时间戳和时区的信息,返回一个datetime对象 print("传入时间戳和时区的信息,返回一个datetime对象",datetime.datetime.fromtimestamp(time.time())) # 日期模块,另外发现日历模块传入的参数也可以使用比如thenyear=2018的这种形式进行传入,也可以直接传入2018的数字进行传入 import calendar print(calendar.calendar(theyear=2018,w=2,l=1,c=6)) # thenyear是年份的表头,w是每日之间的间隔字符数,c是指每月之间的间隔字符数,l是指每个星期的行数 ,返回一个日历,返回整年日历 print("返回每周开始日期,默认是0也就是从星期一开始",calendar.firstweekday()) print("判断参数的年份是不是闰年",calendar.isleap(2018)) # 这个方法有意思,如果不传参数不是默认当前年,而是什么都不返回,如果有参数则返回true或者false print("返回在指定年份之间的闰年数量",calendar.leapdays(2017,2021)) # 这个函数是包含开始年份,但是不包含结束年份的计算 print("返回一个指定年月的日历",calendar.month(theyear=2018,themonth=5,w=2,l=1)) # 也就是返回指定年份和月份的日历,返回正月日历 print("将指定月份按照每一周的日期一个列表的形式进行返回,如果有和其他月份日期交叉的周,其他月份的日期返回为0",calendar.monthcalendar(year=2018,month=5)) print("返回指定年月的起始日期情况",calendar.monthrange(2018,4)) # 经过测试发现,返回两个整数,第一个是该月1号所在星期数(但是总是比实际星期几少1也就是这个返回数字加1才是实际星期数,这个主要是因为周一是0的原因没,在使用的时候需要注意,第二个数是该月的最大日期数,也就是该月的天数) print("没看清作用是啥",calendar.setfirstweekday(0)) print(calendar.weekday(2018,5,17))
'''41. Using calendar module perform following operations. a)print(the 2016 calendar with space between months as 10 character. b) How many leap days between the years 1980 to 2025. c) Check given year is leap year or not. d) print(calendar of any specified month of the year 2016. ''' import calendar for months in range(1,13): print(calendar.month(2016,months) print print("Leap days between 1980 to 2025:", calendar.leapdays(1980, 2026)) print("2017 is leap year:", calendar.isleap(2017)) print("month of 2016:",calendar.month(2016,3))
def test_several_leapyears_in_range(self): self.assertEqual(calendar.leapdays(1997, 2020), 5)
def test_no_range(self): # test when no range i.e. two identical years as args self.assertEqual(calendar.leapdays(2010,2010), 0)
def test_no_leapdays(self): # test when no leap years in range self.assertEqual(calendar.leapdays(2010, 2011), 0)
def test_no_leapdays_upper_boundary(self): # test no leap years in range, when upper boundary is a leap year self.assertEqual(calendar.leapdays(2010,2012), 0)
def test_one_leapday_lower_boundary(self): # test when one leap year in range, lower boundary is leap year self.assertEqual(calendar.leapdays(2012, 2013), 1)
def test_several_leapyears_in_range(self): self.assertEqual(calendar.leapdays(1997,2020), 5)
def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. 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. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, ('year', 'years')), (60 * 60 * 24 * 30, ('month', 'months')), (60 * 60 * 24 * 7, ('week', 'weeks')), (60 * 60 * 24, ('day', 'days')), (60 * 60, ('hour', 'hours')), (60, ('minute', 'minutes')) ) # Convert int or float (unix epoch) to datetime.datetime for comparison if isinstance(d, int) or isinstance(d, float): d = datetime.datetime.fromtimestamp(d) # 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) if not now: now = datetime.datetime.now() # ignore microsecond part of 'd' since we removed it from 'now' delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) delta -= datetime.timedelta(calendar.leapdays(d.year, now.year)) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return u'0 ' + 'minutes' for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break if count == 1: s = '%(number)d %(type)s' % {'number': count, 'type': name[0]} else: s = '%(number)d %(type)s' % {'number': count, 'type': name[1]} if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: if count2 == 1: s += ', %d %s' % (count2, name2[0]) else: s += ', %d %s' % (count2, name2[1]) return s
#!/usr/bin/python import calendar a=int(raw_input("Enter the first year: ")) b=int(raw_input("\nEnter the second year: ")) ''' calendar.leapdays(y1,y2) Returns the total number of leap days in the years within range(y1,y2) ''' cal=calendar.leapdays(a,b) print cal
# -*- coding: utf-8 -*- import calendar start = 2000 end = 2050 uruudosi = calendar.leapdays(start, end) #閏年が何回あるか youbi = calendar.weekday(2016, 7, 29) if youbi == 0: youbi = "月" elif youbi == 1: youbi = "火" elif youbi == 2: youbi = "水" elif youbi == 3: youbi = "木" elif youbi == 4: youbi = "金" elif youbi == 5: youbi = "土" elif youbi == 6: youbi = "日" else: youbi = "エラーです。" print "%s年から%s年までの閏年は全部で %s回です。" % (start, end, uruudosi) print "%s曜日です." % youbi
print time.strftime( '%H', time.localtime() ) # takes str only for current or str and given 9 tupletime return time formated as u given # % a'A day b'B month y'Y yr(shrt'full) names #%d/%m/%y day month year numbers = %x for date but mm/dd/yy %X represent time only # %U wk# in year %j day of year %z time zone name # %c date and time %H hr in 24 print time.strptime('21 november 2015 00:05:05', '%d %B %Y %X') # takes 2 str and return 9 tupletime # strptime(str'must be euqal to given %formate' , str'given %formate') t = [2009, 1, 1, 0, 0, 0, 0, 0, 0] print time.strftime('%d/%m/%Y\t%X', t) from datetime import date print date.today().year print date.today().month print date.today().day '______________________________________________' import calendar calendar.calendar(2000) # print calendar of givien year print calendar.month(2018, 10) # print out month calendar print calendar.isleap(2016) # check leap year return True or False print calendar.leapdays(2000, 2018) # print no. of leap days btw 2 given years print calendar.weekday(2018, 3, 14) # return weekday code of the given date (0=monday)
#日付の計算 import datetime today = datetime.datetime.today() # 今日の日付 print(today) # 明日の日付 print(today + datetime.timedelta(days=1)) newyear = datetime.datetime(2010, 1, 1) # 2010年1月1日の一週間後 print(newyear + datetime.timedelta(days=7)) # 2010年1月1日から今日までの日数 calc = today - newyear # 計算結果の戻り値は「timedelta」 print(calc.days) #うるう年の判定 import calendar print(calendar.isleap(2015)) print(calendar.isleap(2016)) print(calendar.isleap(2017)) print(calendar.leapdays(2010, 2020))
import calendar year = 2015 while not calendar.isleap(year): year= year + 1 print year print calendar.leapdays(2000,2005) print calendar.weekday(2016,7,29)
import calendar import time # printing header of the week, starting from Monday print(calendar.weekheader(9) + "\n") # printing calendar for the a particular month of a year along with spacing between each day print(calendar.month(2020, 4) + "\n") # printing a particular month in 2-D array mode print(calendar.monthcalendar(2020, 4)) print() # printing calendar for the entire year print(calendar.calendar(2020)) print() # printing a particular day of the week in a month in terms of integer print(calendar.weekday( 2020, 4, 12)) # answer is 6, because according to python 6 is Sunday print() # finding whether a year is leap year or not print(calendar.isleap(2020)) print() # finding leap days within specific years, the year you put at the end is exclusive, 2000 and 2004 is leap year. print(calendar.leapdays(2000, 2005))
def calculate_moon_position1(day,month,year,timeH,timeM,timeS): print "Calculated with set date: "+str(day)+"/"+str(month)+"/"+str(year)+"/ at " + str(timeH)+":"+str(timeM)+":"+str(timeS)+".\n" time_as_frac_of_day = ((timeS/60.0 + timeM)/60.0 + timeH)/24.0 daystotal=0 for monthdays in daysinmonth[:month-1]: daystotal += monthdays daystotal += day total_days = (year-1990)*365 + calendar.leapdays(1990, year+1) + daystotal + time_as_frac_of_day Mean_anomaly1 = (360/days_for_360 * total_days) Mean_anomaly1 = adjustrange1(Mean_anomaly1) Mean_anomaly2 = Mean_anomaly1 + Ecliptic_longitude - Ecliptic_longitude_of_perigee if Mean_anomaly2 < 0: Mean_anomaly2 += 360 E_c = (360.0/pi)* eccentricity_of_orbit * math.sin(math.radians(Mean_anomaly2)) SunGeometricEclipticLongitude = Mean_anomaly1 + E_c + Ecliptic_longitude SunGeometricEclipticLongitude = adjustrange1(SunGeometricEclipticLongitude) l = 13.1763966 * total_days + mean_longitude l = adjustrange1(l) M_m = l - 0.1114041 * total_days - mean_longitude_of_perigee M_m = adjustrange1(M_m) N = mean_longitude_of_node - 0.0529539 * total_days N = adjustrange1(N) C = l - SunGeometricEclipticLongitude E_v = 1.2739 * math.sin(math.radians(2*C - M_m)) A_e = 0.1858 * math.sin(math.radians(Mean_anomaly2)) A_3 = 0.37 * math.sin(math.radians(Mean_anomaly2)) Corrected_anomaly = M_m + E_v - A_e - A_3 #M'_m E_c = 6.2886 * math.sin(math.radians(Corrected_anomaly)) A_4 = 0.214 * math.sin(math.radians(2 * Corrected_anomaly)) l_prime = l + E_v + E_c - A_e + A_4 V = 0.6583 * math.sin(math.radians(2*(l_prime - SunGeometricEclipticLongitude))) true_longitude = l_prime + V #l''= l' + V N_prime = N - 0.16 * math.sin(math.radians(Mean_anomaly2)) y = math.sin(math.radians(true_longitude - N_prime)) * math.cos(math.radians(inclination_of_moon_orbit)) x = math.cos(math.radians(true_longitude - N_prime)) tan_yx = math.degrees(math.atan(y/x)) if (x < 0) and (y > 0): if tan_yx > 180: tan_yx -= 180*int(tan_yx/180) elif tan_yx < 90: tan_yx += 180*(abs(int(tan_yx/180))+1) elif (x > 0) and (y > 0): if tan_yx > 90: tan_yx -= 180*int(tan_yx/180) elif tan_yx < 0: tan_yx += 180*(abs(int(tan_yx/180))+1) elif (x > 0) and (y < 0): if tan_yx > 0: tan_yx -= 180*int(tan_yx/180) elif tan_yx < -90: tan_yx += 180*(abs(int(tan_yx/180))+1) elif (x < 0) and (y < 0): if tan_yx > -90: tan_yx -= 180*int(tan_yx/180) elif tan_yx < -180: tan_yx += 180*(abs(int(tan_yx/180))+1) lambda_m = tan_yx + N_prime beta_m = math.degrees(math.asin(math.sin(math.radians(true_longitude - N_prime)) * math.sin(math.radians(inclination_of_moon_orbit)))) if (month == 1) or (month == 2): year2 = year -1 month2 = month +12 else: year2 = year month2= month if datetime.datetime(year,month,day) >= datetime.datetime(1582,10,15): A = int(year2/100) B = 2 - A + int(A/4) else: B = 0 if year2 > 0: C = int(365.25 * year2) else: C = int((365.25 * year2) - 0.75) D = int(30.6001 * (month2 +1)) JD = B + C + D + day + 1720994.5 ##julian days JD -= 2451545 T = JD/36525.0 change_in_mean_obliquity_of_ecliptic = 46.815 * T + 0.0006*T*T - 0.00181*T*T*T change_in_mean_obliquity_of_ecliptic /= 3600.0 mean_obliquity_of_ecliptic = 23.439292 - change_in_mean_obliquity_of_ecliptic alpha_m = math.degrees(math.atan((math.sin(math.radians(lambda_m)) * math.cos(math.radians(mean_obliquity_of_ecliptic)) - math.tan(math.radians(beta_m)) * math.sin(math.radians(mean_obliquity_of_ecliptic)))/math.cos(math.radians(lambda_m)))) alpha_m = adjustrange1(alpha_m)/15.0 alpha_m2 = decdeg2dms(alpha_m) delta_m = math.degrees(math.asin(math.sin(math.radians(beta_m)) * math.cos(math.radians(mean_obliquity_of_ecliptic)) + math.cos(math.radians(beta_m)) * math.sin(math.radians(mean_obliquity_of_ecliptic)) * math.sin(math.radians(lambda_m)))) delta_m2 = decdeg2dms(delta_m) return T,true_longitude,SunGeometricEclipticLongitude,alpha_m,alpha_m2,delta_m,delta_m2
def test_no_leapdays(self): # test when no leap years in range self.assertEqual(calendar.leapdays(2010,2011), 0)
def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 minutes" is returned. 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. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ((60 * 60 * 24 * 365, ('year', 'years')), (60 * 60 * 24 * 30, ('month', 'months')), (60 * 60 * 24 * 7, ('week', 'weeks')), (60 * 60 * 24, ('day', 'days')), (60 * 60, ('hour', 'hours')), (60, ('minute', 'minutes'))) # Convert int or float (unix epoch) to datetime.datetime for comparison if isinstance(d, int) or isinstance(d, float): d = datetime.datetime.fromtimestamp(d) if isinstance(now, int) or isinstance(now, float): now = datetime.datetime.fromtimestamp(now) # 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) if not now: now = datetime.datetime.now() delta = now - (d - datetime.timedelta(0, 0, d.microsecond)) # Deal with leapyears by subtracing the number of leapdays delta -= datetime.timedelta(calendar.leapdays(d.year, now.year)) # ignore microsecond part of 'd' since we removed it from 'now' since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return '0 minutes' for i, (seconds, name) in enumerate(chunks): count = since // seconds if count != 0: break if count == 1: s = '%(number)d %(type)s' % {'number': count, 'type': name[0]} else: s = '%(number)d %(type)s' % {'number': count, 'type': name[1]} if i + 1 < len(chunks): # Now get the second item seconds2, name2 = chunks[i + 1] count2 = (since - (seconds * count)) // seconds2 if count2 != 0: if count2 == 1: s += ', %d %s' % (count2, name2[0]) else: s += ', %d %s' % (count2, name2[1]) return s
def test_one_leapday_lower_boundary(self): # test when one leap year in range, lower boundary is leap year self.assertEqual(calendar.leapdays(2012,2013), 1)
#!/usr/bin/python3 import datetime as d import calendar as c ## principal = float(input("Enter Principle amount:")) interest_rate = float(input("Enter annual interest rate:")) payout_day,payout_month,payout_year=input("..and when do you expect" +" to get it back: year month day:") \ .split() now = d.datetime.now() d0 = d.date(now.year, now.month, now.day) d1 = d.date(int(payout_day), int(payout_month), int(payout_year)) interest = principal * interest_rate * (d1-d0).days \ / ((365 + c.leapdays(d1.year, d0.year))*100) print("Principal:" + str(principal) + ", Interest:" + str(interest) + ", Total:" + str(principal + interest))
def inboxentime(value): """A filter much like Django's timesince and naturaltime, except it only gives the most significant unit. Much of this function was taken from Django 1.11.12 Copyright (c) Django Software Foundation and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ if not isinstance(value, datetime): value = datetime(value.year, value.month, value.day) now = timezone.now() delta = now - value # Deal with leapyears by substracting leapdays leapdays = calendar.leapdays(value.year, now.year) if leapdays != 0: if calendar.isleap(value.year): leapdays -= 1 elif calendar.isleap(now.year): leapdays += 1 delta -= timedelta(leapdays) since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 60: # if it's less than a minute ago, it was just now return avoid_wrapping(_("just now")) for i, (seconds, name) in enumerate(TIMESINCE_CHUNKS): count = since // seconds if count != 0: break name = name % count return avoid_wrapping(name)
import calendar print(calendar.weekheader(3)) print(calendar.month(2021, 3)) print(calendar.calendar(2021)) print(calendar.monthcalendar(2021, 3)) is_leap = calendar.isleap(2020) print(is_leap) how_many = calendar.leapdays(2004, 2009) print(how_many) import datetime import time print(datetime.time(12, 15))