One Python standard library | calendar per week

Keywords: github Python

Technology blog: https://github.com/yongxinz/tech-blog

At the same time, welcome to pay attention to my WeChat public number AlwaysBeta, more wonderful content waiting for you to come.

The calendar module defines the calendar class, which encapsulates the calculation of values, such as the date of the week in a given month or year. In addition, TextCalendar and HTMLCalendar classes can generate pre formatted output.

Format example

The prmonth() method is simple enough to generate one month's formatted text output.

import calendar

c = calendar.TextCalendar(calendar.SUNDAY)
c.prmonth(2017, 7)

# output
#      July 2017
# Su Mo Tu We Th Fr Sa
#                    1
#  2  3  4  5  6  7  8
#  9 10 11 12 13 14 15
# 16 17 18 19 20 21 22
# 23 24 25 26 27 28 29
# 30 31

According to TextCalendar U.S. convention, the example is configured to start the week on Sunday. The default is to use the European Convention of the week beginning Monday.

You can use HTML calendar and formatmonth() to generate HTML like tables. The rendered output looks roughly the same as plain text, but is wrapped in HTML markup. Each table cell has a class property corresponding to the day of the week, so HTML can be styled through CSS.

To generate output in a format different from one of the available default values, use calendar to calculate the date and organize the values into week and month ranges, and then iterate over the results. The weekheader(), monthcalendar(), and yeardays2calendar() methods of the calendar module are particularly useful for this.

A call to yeardays2calendar() generates a list of "month lines.". Each list includes the month as another week list. These weeks are a tuple list of date numbers (1-31) and weekday numbers (0-6). The number of days beyond the month is 0.

import calendar
import pprint

cal = calendar.Calendar(calendar.SUNDAY)

cal_data = cal.yeardays2calendar(2017, 3)
print('len(cal_data)      :', len(cal_data))

top_months = cal_data[0]
print('len(top_months)    :', len(top_months))

first_month = top_months[0]
print('len(first_month)   :', len(first_month))

print('first_month:')
pprint.pprint(first_month, width=65)

# output
# len(cal_data)      : 4
# len(top_months)    : 3
# len(first_month)   : 5
# first_month:
# [[(1, 6), (2, 0), (3, 1), (4, 2), (5, 3), (6, 4), (7, 5)],
#  [(8, 6), (9, 0), (10, 1), (11, 2), (12, 3), (13, 4), (14, 5)],
#  [(15, 6), (16, 0), (17, 1), (18, 2), (19, 3), (20, 4), (21, 5)],
#  [(22, 6), (23, 0), (24, 1), (25, 2), (26, 3), (27, 4), (28, 5)],
#  [(29, 6), (30, 0), (31, 1), (0, 2), (0, 3), (0, 4), (0, 5)]]

Equivalent to using formatyear().

import calendar

cal = calendar.TextCalendar(calendar.SUNDAY)
print(cal.formatyear(2017, 2, 1, 1, 3))

# output
#                               2017
# 
#       January               February               March
# Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
#  1  2  3  4  5  6  7            1  2  3  4            1  2  3  4
#  8  9 10 11 12 13 14   5  6  7  8  9 10 11   5  6  7  8  9 10 11
# 15 16 17 18 19 20 21  12 13 14 15 16 17 18  12 13 14 15 16 17 18
# 22 23 24 25 26 27 28  19 20 21 22 23 24 25  19 20 21 22 23 24 25
# 29 30 31              26 27 28              26 27 28 29 30 31
# 
#        April                  May                   June
# Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
#                    1      1  2  3  4  5  6               1  2  3
#  2  3  4  5  6  7  8   7  8  9 10 11 12 13   4  5  6  7  8  9 10
#  9 10 11 12 13 14 15  14 15 16 17 18 19 20  11 12 13 14 15 16 17
# 16 17 18 19 20 21 22  21 22 23 24 25 26 27  18 19 20 21 22 23 24
# 23 24 25 26 27 28 29  28 29 30 31           25 26 27 28 29 30
# 30
# 
#         July                 August              September
# Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
#                    1         1  2  3  4  5                  1  2
#  2  3  4  5  6  7  8   6  7  8  9 10 11 12   3  4  5  6  7  8  9
#  9 10 11 12 13 14 15  13 14 15 16 17 18 19  10 11 12 13 14 15 16
# 16 17 18 19 20 21 22  20 21 22 23 24 25 26  17 18 19 20 21 22 23
# 23 24 25 26 27 28 29  27 28 29 30 31        24 25 26 27 28 29 30
# 30 31
# 
#       October               November              December
# Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
#  1  2  3  4  5  6  7            1  2  3  4                  1  2
#  8  9 10 11 12 13 14   5  6  7  8  9 10 11   3  4  5  6  7  8  9
# 15 16 17 18 19 20 21  12 13 14 15 16 17 18  10 11 12 13 14 15 16
# 22 23 24 25 26 27 28  19 20 21 22 23 24 25  17 18 19 20 21 22 23
# 29 30 31              26 27 28 29 30        24 25 26 27 28 29 30
#                                             31

The day ABCD name, day ABCD, month ABCD name, and month ABCD modules are mainly used to produce custom formatted output (that is, including links in HTML output). They are automatically configured for the current area.

Zone setup

If you want to generate a formatted calendar for a non default area, you can use LocaleTextCalendar or localehtml calendar.

import calendar

c = calendar.LocaleTextCalendar(locale='en_US')
c.prmonth(2017, 7)

print()

c = calendar.LocaleTextCalendar(locale='fr_FR')
c.prmonth(2017, 7)

# output
#      July 2017
# Mo Tu We Th Fr Sa Su
#                 1  2
#  3  4  5  6  7  8  9
# 10 11 12 13 14 15 16
# 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30
# 31
#
#     juillet 2017
# Lu Ma Me Je Ve Sa Di
#                 1  2
#  3  4  5  6  7  8  9
# 10 11 12 13 14 15 16
# 17 18 19 20 21 22 23
# 24 25 26 27 28 29 30
# 31

The first day of the week is not part of the locale settings, and this value is a parameter of the class, just like TextCalendar.

Date of calculation

While the calendar module focuses primarily on printing a complete calendar in various formats, it also provides useful functionality to process dates in other ways, such as calculating the dates of recurring events.

For example, the Python Atlanta user group meets on the second Thursday of each month. To calculate the meeting date for a year, use monthcalendar().

import calendar
import pprint

pprint.pprint(calendar.monthcalendar(2017, 7))

# output
# [[0, 0, 0, 0, 0, 1, 2],
#  [3, 4, 5, 6, 7, 8, 9],
#  [10, 11, 12, 13, 14, 15, 16],
#  [17, 18, 19, 20, 21, 22, 23],
#  [24, 25, 26, 27, 28, 29, 30],
#  [31, 0, 0, 0, 0, 0, 0]]

A value of 0 is the time of the week that overlaps a given month and is part of another month.

The first day of the week defaults to Monday. You can change this by calling setfirstweekday(), but because the calendar module contains the constant monthcalendar() for the date range returned by the index, it is more convenient to skip this step in this case.

To calculate the group meeting dates for a year, suppose they are always on the second Thursday of each month, look at the output of monthcalendar() to find Thursday. Fill the first and last week of the month with a value of 0 as a placeholder for the number of days in the previous or next month. For example, if a month starts on Friday, the value of the first week of the Thursday position will be 0.

import calendar
import sys

year = int(sys.argv[1])

# Show every month
for month in range(1, 13):

    # Compute the dates for each week that overlaps the month
    c = calendar.monthcalendar(year, month)
    first_week = c[0]
    second_week = c[1]
    third_week = c[2]

    # If there is a Thursday in the first week,
    # the second Thursday is # in the second week.
    # Otherwise, the second Thursday must be in
    # the third week.
    if first_week[calendar.THURSDAY]:
        meeting_date = second_week[calendar.THURSDAY]
    else:
        meeting_date = third_week[calendar.THURSDAY]

    print('{:>3}: {:>2}'.format(calendar.month_abbr[month], meeting_date))

# output    
# Jan: 12
# Feb:  9
# Mar:  9
# Apr: 13
# May: 11
# Jun:  8
# Jul: 13
# Aug: 10
# Sep: 14
# Oct: 12
# Nov:  9
# Dec: 14

List of other functions that may be useful

Serial number Functions and descriptions
1 calendar.calendar(year,w=2,l=1,c=6) returns the year year calendar in the format of a multi line string, with a line of three months and an interval of c. The daily width interval is w characters. The length of each line is 21* W+18+2* C. L is the number of lines per week.
2 calendar.firstweekday() returns the setting for the start date of the current week. By default, 0 is returned when the calendar module is first loaded, Monday.
3 Calendar.islap (year) returns True if it is a leap year, otherwise it is false.
4 calendar.leapdays(y1,y2) returns the total number of leap years between Y1 and Y2.
5 calendar.month(year,month,w=2,l=1) returns a multi line string format year month monthly calendar, with two line titles and one week line. The daily width interval is w characters. The length of each row is 7* w+6. L is the number of lines per week.
6 calendar.monthcalendar(year,month) returns a single nested list of integers. Each sublist load represents an integer for a week. The date outside month of Year is set to 0; the days in the range are represented by the day of the month, starting from 1.
7 Calendar.month (year, month) returns two integers. The first is the date code of the day of the week of the month, and the second is the date code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6) is equivalent to print calendar.calendar(year,w,l,c)
9 calendar.prmonth(year,month,w=2,l=1) is equivalent to print calendar.calendar (year, W, l, c).
10 calendar.setfirstweekday(weekday) sets the start date code for the week. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime) and time.gmtime are the opposite: accept a time tuple and return the time dropout (floating-point seconds after the 1970 era).
12 calendar.weekday(year,month,day) returns the date code of a given date. 0 (Monday) to 6 (Sunday). The months are from January to December.

Related documents:

https://pymotw.com/3/calendar/index.html

https://www.imooc.com/wiki/detail/id/1911

15 original articles published, 30 praised, 40000 visitors+
Private letter follow

Posted by ionik on Tue, 21 Jan 2020 01:55:36 -0800