美文网首页
Python 实现日历的方法

Python 实现日历的方法

作者: xstalk | 来源:发表于2018-07-02 23:52 被阅读0次

    Python 实现日历方法

    感觉写的很乱,又冗余,应该有简洁的代码实现

    # -*- coding:utf-8 -*-
    import time, calendar, datetime
    
    def print_top_month(year, month, day):
        print('今天是%s年%s月%s日' %(year, month, day))
        print('-------------------------------------')
        print ('    日  一   二   三   四   五   六')
    
    def start_day(year, month):
        '''获取每月第一天是周几和当月总天数'''
        # monthCount = calendar.monthrange(dateNow.year, dateNow.month)
        monthCount = calendar.monthrange(int(year), int(month))
        return monthCount[0]+1,monthCount[1]
    
    def before_month(month):
        # 上个月的日期
        b_y,b_m = start_day(year, month-1)
        i,u = start_day(year, month)
        before_day = list(range(1,b_m+1))[-i:]
        for f in before_day:
            print('%5d' %f,end='')
    
    def print_date(year, month):
        i,u = start_day(year, month)
        # if i != 7:
        #     print ('     '* i,end='')
        if i != 7:
            before_month(month)
        for t in range(1, u+1):
            print ('%5d' %t,end='')
            i += 1
            if i % 7 == 0:
                print (' ')
        if i % 7 != 0:
            after_month(year, month)
    
    def after_month(year, month):
    # 下个月的日期
        if month != 12:
            a_y,a_m = start_day(year, month+1)
            i,u = start_day(year, month)
            after_week = (calendar.weekday(year,month,u))+1
            if after_week != 7:
                o = 6-after_week
            else:
                o = 6                   
            after_day = list(range(1,a_m+1))[:o]
            for f in after_day:
                print('%5d' %f,end='')       
    
    
    # 获取当前日期
    # dateNow = datetime.datetime.now()
    # year = dateNow.year
    # month = dateNow.month
    # day = dateNow.day
    
    # 获取用户输入日期
    # year, month, day = map(int,input('Please inpurt date:').split(','))
    
    # 自定义日期
    year, month, day = 2018, 8, 6
    
    print_top_month(year, month, day)
    print_date(year, month)
    # after_month(year, month)
    
    

    相关文章

      网友评论

          本文标题:Python 实现日历的方法

          本文链接:https://www.haomeiwen.com/subject/tabruftx.html