在不导入日历的情况下制作年历

时间:2015-11-10 06:36:15

标签: python python-3.x calendar

编写一个给出的函数:

  1. 一年

  2. 当年1/1的一周。

  3. 该功能应打印该年度的年度日历

    实施例: enter image description here

    还要考虑闰年。可以被4整除但不是100的一年是闰年!如果它可以被400整除,那么它是闰年。 示例:1900可以被4和100整除,但它不是闰年。 2000可被4和100“AND 400”整除,这是闰年。

    在制作此日历时考虑闰年。

2 个答案:

答案 0 :(得分:4)

我想这应该就是这样做的。

# List of tuples for Months and date ranges
# + 1 added to avoid confusion of max day range
calender = [('January', range(1, 31 + 1)),
            ('Feburary', range(1, 28 + 1)),
            ('March', range(1, 31 + 1)),
            ('April', range(1, 30 + 1)),
            ('May', range(1, 31 + 1)),
            ('June', range(1, 30 + 1)),
            ('July', range(1, 31 + 1)),
            ('August', range(1, 31 + 1)),
            ('September', range(1, 30 + 1)),
            ('October', range(1, 31 + 1)),
            ('November', range(1, 30 + 1)),
            ('December', range(1, 31 + 1))]

week = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']

def make_calendar(year, start_day):
    """
    make_calendar(int, str) --> None
    """
    # Determine current starting position on calendar
    start_pos = week.index(start_day)

    # if True, adjust Feburary date range for leap year | 29 days
    if is_leap(year):
        calender[1] = ('Feburary', range(1, 29 + 1))

    for month, days in calender:
        # Print month title
        print('{0} {1}'.format(month, year).center(20, ' '))
        # Print Day headings
        print(''.join(['{0:<3}'.format(w) for w in week]))
        # Add spacing for non-zero starting position
        print('{0:<3}'.format('')*start_pos, end='')

        for day in days:
            # Print day
            print('{0:<3}'.format(day), end='')
            start_pos += 1
            if start_pos == 7:
                # If start_pos == 7 (Sunday) start new line
                print()
                start_pos = 0 # Reset counter
        print('\n')

def is_leap(year):
    """Checks if year is a leap year"""
    if year % 4 == 0:
        if year % 100 == 0:
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False
yr=int(input('Enter Year'))
strtday=input('Enter start day of the year Mo,Tu,We,Th,Fr,Sa,Su')
make_calendar(yr,strtday)

答案 1 :(得分:1)

这是备用日历,它使用datetime模块获取给定年份和月份中的星期几。相似的代码体,只是实现方式略有不同。

ln -sf /usr/bin/python3.8 /usr/bin/python
相关问题