This article describes how to generate a calendar in python and how to implement the calendar module in python. For more information about how to generate a calendar in Python, see the following example. This instance can generate a 5x7 list for a calendar month. No date in the list is of the datetime type and is implemented using the calendar module provided by python.
The program running result is as follows:
python test.py 2014 09 2014-08-31 2014-09-01 2014-09-02 2014-09-03 2014-09-04 2014-09-05 2014-09-06 2014-09-07 2014-09-08 2014-09-09 2014-09-10 2014-09-11 2014-09-12 2014-09-13 2014-09-14 2014-09-15 2014-09-16 2014-09-17 2014-09-18 2014-09-19 2014-09-20 2014-09-21 2014-09-22 2014-09-23 2014-09-24 2014-09-25 2014-09-26 2014-09-27 2014-09-28 2014-09-29 2014-09-30 2014-10-01 2014-10-02 2014-10-03 2014-10-04
The python code is as follows:
# Coding: UTF-8 # Last modified: 11:08:08 import calendar import datetime import sys def getcal (y, m): # from Sunday onwards cal = calendar. calendar (6) if not isinstance (y, int): y = int (y) if not isinstance (m, int): m = int (m) if m = 1: # py = y-1 in March; pm = 12; ny = y; nm = 2 elif m = 12: # py = y in March; pm = 11 ny = y + 1; nm = 1 else: py = y; pm = m-1 ny = y; nm = m + 1 pcal = cal. monthdayscalendar (py, pm) # ncal = cal. monthdayscalendar (ny, nm) # ccal = cal next month. monthdayscalendar (y, m) # current w1 = ccal. pop (0) # obtain the first week w2 = ccal. pop () # obtain wp = pcal for the last week. pop () # wn = ncal in the last week of last month. pop (0) # The first week of the next month # r1 = [datetime. date (y, m, w1 [I]) or wp [I] for I in range (7)] r1 = [w1 [I] and datetime. date (y, m, w1 [I]) or datetime. date (py, pm, wp [I]) for I in range (7)] r2 = [w2 [I] and datetime. date (y, m, w2 [I]) or datetime. date (ny, nm, wn [I]) for I in range (7)] # convert datetime result = [] result. append (r1) # week 1 for c in ccal: # result of other weeks. append ([datetime. date (y, m, I) for I in c]) result. append (r2) # return result if _ name _ = '_ main _' in the last week: for w in getcal (sys. argv [1], sys. argv [2]): for d in w: print d, print
I hope the examples described in this article will help you with Python program design.