Промышленное производство
Промышленный Интернет вещей | Промышленные материалы | Техническое обслуживание и ремонт оборудования | Промышленное программирование |
home  MfgRobots >> Промышленное производство >  >> Industrial programming >> Python

Учебник Python CALENDAR с примером

Модуль календаря в Python имеет класс календаря, который позволяет выполнять вычисления для различных задач на основе даты, месяца и года. Кроме того, классы TextCalendar и HTMLCalendar в Python позволяют редактировать календарь и использовать его в соответствии с вашими требованиями.

Давайте посмотрим, что мы можем сделать с календарем Python.

Шаг 1) Запустите код.

Давайте быстро изменим значение с воскресенья на четверг и проверим вывод

Шаг 2) Вы также можете распечатать Календарь в формате HTML, эта функция полезна для разработчиков, если они хотят внести какие-либо изменения во внешний вид календаря

Шаг 3) Перебирает дни месяца с помощью c.itermonthday (2025,4), он получает общее количество дней в этом месяце.

Шаг 4) Вы можете получить данные из локальной системы, например месяцы или дни недели и т. д.

Шаг 5) Вы можете получить список определенного дня в течение всего года. Например, каждый первый понедельник недели день аудита. Вы хотите узнать дату первого понедельника каждого месяца. Вы можете использовать этот код

Вот полный код

Пример Python 2

import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print str

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print str
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print i

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print name
    for day in calendar.day_name:
        print day
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print "%10s %2d" % (calendar.month_name[month], auditday)

Пример Python 3

import calendar
# Create a plain text calendar
c = calendar.TextCalendar(calendar.THURSDAY)
str = c.formatmonth(2025, 1, 0, 0)
print(str)

# Create an HTML formatted calendar
hc = calendar.HTMLCalendar(calendar.THURSDAY)
str = hc.formatmonth(2025, 1)
print(str)
# loop over the days of a month
# zeroes indicate that the day of the week is in a next month or overlapping month
for i in c.itermonthdays(2025, 4):
    print(i)

    # The calendar can give info based on local such a names of days and months (full and abbreviated forms)
    for name in calendar.month_name:
        print(name)
    for day in calendar.day_name:
        print(day)
    # calculate days based on a rule: For instance an audit day on the second Monday of every month
    # Figure out what days that would be for each month, we can use the script as shown here
    for month in range(1, 13):
		# It retrieves a list of weeks that represent the month
        mycal = calendar.monthcalendar(2025, month)
		# The first MONDAY has to be within the first two weeks
        week1 = mycal[0]
        week2 = mycal[1]
        if week1[calendar.MONDAY] != 0:
            auditday = week1[calendar.MONDAY]
        else:
        # if the first MONDAY isn't in the first week, it must be in the second week
        	auditday = week2[calendar.MONDAY]
print("%10s %2d" % (calendar.month_name[month], auditday))

Обзор:


Python

  1. Учебное пособие по абстрактному классу C # с примером:что такое абстракция?
  2. Функция Python String strip() с ПРИМЕРОМ
  3. Количество строк Python() с ПРИМЕРАМИ
  4. Функция Python round() с ПРИМЕРАМИ
  5. Функция Python map() с ПРИМЕРАМИ
  6. Python Timeit() с примерами
  7. Учебное пособие по доходности в Python:генератор и пример доходности и возврата
  8. Счетчик Python в коллекциях с примером
  9. Счетчик списка Python() с ПРИМЕРАМИ
  10. Индекс списка Python() с примером