Python generates calendar instance resolution
- 2020-04-02 13:58:20
- OfStack
This article demonstrates an example of how to implement a Python generated calendar. This example implements a calendar for a month to generate a 5x7 list of datetime dates, using python's built-in calendar module.
The results of the program are 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: 2014-08-21 11:08:08
import calendar
import datetime
import sys
def getcal(y, m):
# Starting Sunday
cal = calendar.Calendar(6)
if not isinstance(y, int): y = int(y)
if not isinstance(m, int): m = int(m)
if m == 1: # 1 in
py = y - 1; pm = 12;
ny = y; nm = 2
elif m == 12: # 12 in
py = y; pm = 11
ny = y + 1; nm = 1
else:
py = y; pm = m - 1
ny = y; nm = m + 1
pcal = cal.monthdayscalendar(py, pm) # On January
ncal = cal.monthdayscalendar(ny, nm) # Next month
ccal = cal.monthdayscalendar(y, m) # The current
w1 = ccal.pop(0) # Take the first week
w2 = ccal.pop() # Last week
wp = pcal.pop() # Last week of last month
wn = ncal.pop(0) # The first week of 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)]
# turn datetime
result = []
result.append(r1) # The first week
for c in ccal: # The other week
result.append([datetime.date(y,m,i) for i in c])
result.append(r2) # The last week
return result
if __name__ == '__main__':
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 are helpful for your Python programming.