[Python module] date time

In normal development work, we often need to use date and time, such as log records, calculation of date and time, assignment of time fields, etc. Python provides built-in modules such as time module, datatime module and submodules, and calendar module, which can realize common operations such as setting, obtaining, and converting date and time.

1. Terms related to date and time

When it comes to date and time, it is necessary to sort out the meaning of related terms first, which is helpful for understanding and usage. Common terms are:

1. Epoch time (new era time)

Indicates the starting point of the time. The value of this time point is different on different platforms. For Unix, the epoch time is 1970-01-01 00:00:00 UTC.

2. UTC time (Universal Coordinated Time)

UTC is the abbreviation of Universal Coordinated Time, also known as GMT (Greenwich Mean Time - Greenwich Mean Time). UTC is the basis of modern timekeeping. It provides a common baseline for the conversion between accumulated time and local time. UTC time is usually represented by Z.

Using Greenwich (prime meridian) as the world's starting point for calculating time and longitude, UTC has a time zone offset of 0. The time in East N Zone is N hours earlier than UTC time, that is, UTC time + N hours is the local time in East N Zone; while the time in West N Zone is N hours later than UTC time, that is, UTC time - N hours is the local time in West N Zone local time.

Generally speaking, Beijing time (a type of local time) refers to the fact that Beijing, China is located in the East Eighth District, which is 8 hours earlier than UTC time, and Beijing time is represented by UTC+8.

3. timestamp (time stamp)

Also known as Unix time or POSIX time, timestamp is a way of expressing time, indicating the number of milliseconds elapsed from 0:00:00 on January 1, 1970 GMT to now (note that some programming languages related methods return the number of seconds). Timestamps are essentially time delta values, which are time zone independent.

4. Display time format

When using the display time format to express the meaning of time, the date and time need to be expressed separately, which can be divided into year, month, day, hour, minute, second, etc. For example, the current Beijing time is: 2022/11/26 18:16:59 .

Currently, the ISO 8601 standard is used to describe the display time format. The global date and time are written as follows: 8-digit date format, T or space, 4-9 digits of time, using Z or +/- 2 digits for time zone offset, seconds (optional ) , as follows:

2022-11-26T19:10:59.123+08
2022-11-26 19:10:59-08
2022-11-26 19:10:59Z
2022-11-26 19:10:00.123+23:45

It should be noted that the display time format is also related to a specific calendar. There are different calendars in different places in the world, and the meaning of expressing time will also be different. For example: the Gregorian calendar has the difference between ordinary years and leap years; some religious calendars will start with certain important figures (xxx II), etc. .

However, we can also use timestamps to express the meaning of time, but the time format is not shown to look simple and friendly.

5. Time zone, time zone offset, daylight saving time (DST)

A time zone is a set of rules used to determine local time, relative to the cumulative time in a particular geographic area. Cumulative time is a way of marking time in a computer, an integral unit of time accumulated from a specific point in time (also called "epoch") to the current time.

If relative to local time, the time zone offset and any daylight savings changes must be taken into account in the time zone rules.

The time zone offset is a quantity that is obtained by adding and subtracting based on UTC time according to the position of various parts of the world relative to the prime meridian. Usually the offset is in 1-hour intervals, but it can be different, such as 30 minutes or 45 minutes. The representation of the time zone offset is usually + or - offset after the time format. For example, the offset of Beijing time can be expressed as: 2022-11-26 18:20:20+08:00.

Daylight Saving Time (DST) , also known as "summer time", is mainly designed to allow people more hours of sunlight at night. Daylight saving time is different in different countries (even DST in some parts of a country is different), and often due to some special events, a one-time modification is made. At the same time, not all regions observe daylight saving time, and generally areas close to the equator do not need daylight saving time. When doing time conversion, it is very important to know when the local DST is introduced, when it is abolished, and when the DST starts and ends (may vary from year to year).

6. Flotation time

Float time only represents a nominal time, which will be presented in the same way in all time zones around the world. It does not correspond to a clear cumulative time. We usually call this kind of time float time .

Flotation date and time representation:

# 和全球时间和日期格式一致, 但没有时区偏移量信息
2022-11-26T19:10:59.123
2022-11-26 19:10:59

The floating time does not belong to a specific time zone. When the corresponding time zone information is bound, the floating time will generate a series of accumulative time values ​​that can be received. It is helpful to give some examples of flotation time events, such as clocking in at 8 o'clock in the morning, the opening time of the World Cup in Qatar, the new season of Glory of Kings tomorrow, etc., all of which do not need to consider time zones.

At this point, after understanding and familiarizing with the meaning of related date and time terms, you can play around.

Two, time module

The time module is used to obtain and convert time types, and time types are roughly divided into: time string, time stamp, and time tuple , with the following characteristics:

  • Time string: output the time in the specified format, such as 20221126235959.
  • Timestamp: refers to the number of seconds elapsed from 0:00:00 on January 1, 1970 (usually the unit is milliseconds, while Python is seconds).
  • Time tuple: use tuple structure to save date and time, such as time.struct_time(tm_year=2022, tm_mon=11, tm_mday=26, tm_hour=19, tm_min=20, tm_sec=59, tm_wday=6, tm_yday=350, tm_isdst =0).

2.1 Date and time formatting

Parameter options and their meanings are as follows:

Commonly used time and date formats are: %Y-%m-%d %H:%M:%S, %Y/%m/%d %H:%M:%S, %Y%m%d%H% M%S.

2.2 Time strings

The methods to obtain the time string are: ctime(), asctime(), the default format is: week month day hour: minute: second year.

# WARNING:root:当前时间(字符串): Sun Nov 27 10:54:55 2022, type: <class 'str'>
logging.warning(f'当前时间(字符串): {time.ctime()}, type: {type(time.ctime())}')
# WARNING:root:当前时间(字符串): Sun Nov 27 10:54:55 2022, type: <class 'str'>
logging.warning(f'当前时间(字符串): {time.asctime()}, type: {type(time.asctime())}')

2.3 Timestamp

The essence of the timestamp is the time difference, because the default time unit is seconds, and the return type is float. The methods for obtaining the timestamp are: time(), time_ns().

# WARNING:root:当前时间(时间戳,单位秒): 1669517695.3470187, type: <class 'float'>
logging.warning(f'当前时间(时间戳,单位秒): {time.time()}, type: {type(time.time())}')
# WARNING:root:当前时间(时间戳,单位纳秒): 1669517695347018700, type: <class 'int'>
logging.warning(f'当前时间(时间戳,单位纳秒): {time.time_ns()}, type: {type(time.time_ns())}')

2.4 Time tuple

Also known as a time array, it takes the tuple type as a parameter or returns a result. The methods for obtaining a date tuple are: mgtime(), localtime(), the former is UTC time, and the latter is local time.

# 返回UTC时间
logging.warning(f'当前时间(时间元组): {time.gmtime()}, \ntype: {type(time.gmtime())}')
# 返回本地时间
logging.warning(f'当前时间(时间元组): {time.localtime()}, \ntype: {type(time.localtime())}')

The log prints as follows:

2.5 Conversion between the three

Time strings, timestamps, and time tuples can be converted to each other. The conversion method is as follows:

<1>, time string to time tuple

# WARNING:root:当前时间(字符串转时间元组): time.struct_time(tm_year=2022, tm_mon=10, tm_mday=1, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=5, tm_yday=274, tm_isdst=-1)
format1 = "%Y%m%d%H%M%S"
logging.warning(f'当前时间(字符串转时间元组): {time.strptime("20221001235959", format1)}')

<2>, time tuple to time string (there are 2 conversion methods)

# WARNING:root:当前时间(时间元组转时间字符串): 2022-11-27 11:09:43
format2 = "%Y-%m-%d %H:%M:%S"
logging.warning(f'当前时间(时间元组转时间字符串): {time.strftime(format2, time.localtime())}')

# WARNING:root:当前时间(时间元组转时间字符串): Sun Nov 27 11:09:43 2022
logging.warning(f'当前时间(时间元组转时间字符串): {time.asctime(time.localtime())}')

<3>, time tuple to timestamp (the value after the decimal point will be truncated)

# WARNING:root:当前时间(时间元组转时间戳): 1669518803.0
logging.warning(f'当前时间(时间元组转时间戳): {time.mktime(time.localtime())}')
# WARNING:root:当前时间(时间戳): 1669518803.9799008
logging.warning(f'当前时间(时间戳): {time.time()}')

<4>, time stamp to time tuple

# WARNING:root:当前时间(时间戳转时间元组): time.struct_time(tm_year=2022, tm_mon=11, tm_mday=27, tm_hour=11, tm_min=17, tm_sec=55, tm_wday=6, tm_yday=331, tm_isdst=0)
logging.warning(f'当前时间(时间戳转时间元组): {time.localtime(time.time())}')
# OSError: [Errno 22] Invalid argument
logging.warning(f'当前时间(时间戳转时间元组): {time.localtime(time.time_ns())}')

With the above four conversions, it is easy to convert time strings to timestamps, or timestamps to time strings.

2.6 Other APIs

The relevant properties related to time zone are:

  • time.altzone: Returns the offset seconds for the DST zone west of Greenwich;
  • time.timezone: Returns the offset seconds from Greenwich in the local time zone (without DST enabled);
  • time.tzname: returns the current standard time & regional daylight saving time;
# -32400
logging.warning(f'其他API(时区偏移秒数,考虑夏令时): {time.altzone}')
# -28800
logging.warning(f'其他API(时区偏移秒数,未考虑夏令时): {time.timezone}')
#  ('中国标准时间', '中国夏令时')
logging.warning(f'其他API(当前标准时间&地区夏令时): {time.tzname}')

The methods of dormancy and time-consuming statistics are:

  • time.sleep(seconds): Set the sleep time (in seconds);
  • time.perf_counter(): used for time-consuming statistical calculations (in seconds);
  • time.perf_counter_ns(): used for time-consuming statistical calculations (in nanoseconds);
start = time.perf_counter_ns()
time.sleep(10)
end = time.perf_counter_ns()
# WARNING:root:其他API(休眠10s,耗时统计): 10.0022121
logging.warning(f'其他API(休眠10s,耗时统计): {end - start}')

Methods related to process and thread time counting are (timing does not include sleep time):

  • process_time(): Returns the sum of the system and user CPU time of the current process (in seconds);
  • process_time_ns(): Returns the sum of the system and user CPU time of the current process (in nanoseconds);
  • thread_time(): returns the sum of the system and user CPU time of the current thread (in seconds);
  • thread_time_ns(): returns the sum of the system and user CPU time of the current thread (in nanoseconds);
# 0.265625,float类型
logging.warning(f'其他API(进程): {time.process_time()}')
# 265625000,int类型
logging.warning(f'其他API(进程): {time.process_time_ns()}')
# 0.265625,float类型
logging.warning(f'其他API(线程): {time.thread_time()}')
# 265625000,int类型
logging.warning(f'其他API(线程): {time.thread_time_ns()}')

3. datatime module and submodules

This module also includes sub-modules such as date/time/datetime/time interval/time zone and time zone information. Modules such as date/time/datetime divide the time in a more refined manner; the timedelta module provides many calculation operations on date and time; modules such as timezone/tzinfo are related to time zones, and which module is usually used to import the submodule.

3.1 date/time/datetime submodule

The datetime.date module provides an API for dates (year-month-day).

The methods for constructing and obtaining date and day of the week are:

# 2022-11-27
print(f'日期API(构造日期): {date(2022, month=11, day=27)}')
today = date.today()
print(f'日期API(年-月-日): {today}')
print(f'日期API(年-月-日,格式化): {date.isoformat(today)}')
# Return a 3-tuple containing ISO year, week number, and weekday
# 日期API(年月日,格式化): (2022, 47, 7)
print(f'日期API(年月日,格式化): {date.isocalendar(today)}')
# 星期天
print(f'日期API(星期几): {today.weekday()+1}')
print(f'日期API(星期几): {today.isoweekday()}')

The conversion methods of the date format are:

today = date.today()
# Mon Nov 28 00:00:00 2022
print(f'日期API(转日期字符串,默认格式): {date.ctime(today)}')
# 2022/11/28
print(f'日期API(转日期字符串,指定格式): {date.strftime(today, "%Y/%m/%d")}')
# time.struct_time(tm_year=2022, tm_mon=11, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=332, tm_isdst=-1)
print(f'日期API(转元组): {date.timetuple(today)}')
# 738487
print(f'日期API(转数字序列): {date.toordinal(today)}')
print(f'日期API(数字序列转日期): {date.fromordinal(738487)}')
# 2022-11-28,time为time模块的导入,而非datetime子模块time
print(f'日期API(时间戳转日期): {date.fromtimestamp(time.time())}')

Properties of the date:

today = date.today()
# 2022-11-28
print(f'日期API(年-月-日): {today.year}-{today.month}-{today.day}')
# 1 day, 0:00:00
print(f'日期API(当前日期最小单位): {today.resolution}')
# 9999-12-31
print(f'日期API(当前日期最大值): {today.max}')
# 0001-01-01
print(f'日期API(当前日期最小值): {today.min}')

The datetime.time module provides an API for time (year, minute, and second), as follows:

current_time = time(11, 59, 59)
print(f'时间API(当前时间):{time.isoformat(current_time)}')
print(f'时间API(当前时间):{time.fromisoformat(str(current_time))}')
print(f'时间API(当前时间):{time.strftime(current_time,"%H/%M/%S")}')
# 0:00:00.000001
print(f'当前时间最小单位:{current_time.resolution}')
# 【00:00:00,23:59:59.999999】
print(f'当前时间区间为:【{current_time.min},{current_time.max}】')
# 11/59/59
print(f'当前时间为:{current_time.hour}/{current_time.minute}/{current_time.second}')

The datetime.datetime module provides an API for time (year, month, day, hour, minute, and second).

API for time date and week (local time):

# 构造日期时间
current_datetime = datetime(year=2022, month=11, day=28, hour=11, minute=59, second=59)
# 2022-11-28 08:13:40.093939
print(f'今天:{datetime.today()}')
print(f'当前日期时间:{datetime.now()}')
# 2022-11-28T08:13:40.093938
print(f'当前时间(标准时间,带T):{datetime.isoformat(datetime.now())}')
# 2022-11-28
print(f'当前日期:{datetime.date(datetime.now())}')
# 08:13:40.093938
print(f'当前时间:{datetime.time(datetime.now())}')
# 1
print(f'当前日期时间的星期:{datetime.isoweekday(datetime.now())}')
print(f'当前日期时间的星期:{datetime.weekday(datetime.now())+1}')

Use UTC time, as follows:

"""UTC时间"""
printg(f'当前日期时间(utc):{datetime.utcnow()}')
print(f'当前日期时间元组(utc):{datetime.utctimetuple(datetime.utcnow())}')
print(f'当前时间戳(utc):{datetime.utcfromtimestamp(current_timestamp)}')

The conversion of date and time formats is as follows:

now = datetime.now()
# 20221128200116
print(f'日期时间对象(转字符串):{datetime.strftime(now, "%Y%m%d%H%M%S")}')
# 2022-11-28 20:01:16
print(f'当前日期时间字符串(转日期时间对象):{datetime.strptime(str(now).split(".")[0], "%Y-%m-%d %H:%M:%S")}')
# 1669636876.113206
print(f'日期时间对象(转时间戳):{datetime.timestamp(now)}')
# 2022-11-28 20:01:16.113206
print(f'时间戳(转日期时间对象):{datetime.fromtimestamp(datetime.timestamp(now))}')
# time.struct_time(tm_year=2022, tm_mon=11, tm_mday=28, tm_hour=20, tm_min=0, tm_sec=32, tm_wday=0, tm_yday=332, tm_isdst=-1)
print(f'日期时间对象(转时间元组):{datetime.timetuple(now)}')
# (2022, 48, 1)
print(f'日期时间对象(转时间元组):{datetime.isocalendar(datetime.now())}')
# 2022-11-28 00:00:00
print(f'当前日期:{datetime.fromisocalendar(year=2022, week=48, day=1)}')
# 738487
print(f'日期时间对象(转数字序列):{datetime.toordinal(now)}')
# 2022-11-28 00:00:00
print(f'数字序列(转日期时间对象):{datetime.fromordinal(datetime.toordinal(now))}')

3.2 timedelta submodule

This module is used to calculate date time addition and subtraction and the interval between two date times.

The addition and subtraction of date and time are as follows:

"""日期时间的加减"""
ctime = datetime.now()
print(f'当前日期时间减去1天:{ctime + timedelta(days=-1)}')
print(f'当前日期时间减去1秒:{ctime + timedelta(seconds=-1)}')
print(f'当前日期时间减去1微秒:{ctime + timedelta(microseconds=-1)}')
print(f'当前日期时间减去1毫秒:{ctime + timedelta(milliseconds=-1)}')
print(f'当前日期时间减去1分钟:{ctime + timedelta(minutes=-1)}')
print(f'当前日期时间减去1小时:{ctime + timedelta(hours=-1)}')
print(f'当前日期时间减去1周:{ctime + timedelta(weeks=-1)}')
# 加法类似
print(f'当前日期时间加上1天:{ctime + timedelta(days=1)}')

The number of intervals between two datetimes is calculated as follows:

"""日期时间的间隔计算"""
ctime = datetime.now()
befor_time = ctime + timedelta(days=-1, hours=5, seconds=30)
print(f'两个时间的间隔天数:{(ctime - befor_time).days}')
print(f'两个时间的间隔分钟数:{(ctime - befor_time).min}')
print(f'两个时间的间隔秒数:{(ctime - befor_time).seconds}')
print(f'两个时间的间隔微秒数:{(ctime - befor_time).microseconds}')
print(f'两个时间的间隔总秒数:{(ctime - befor_time).total_seconds()}')

3.3 timezone submodule

This module is used to obtain time zone information, as follows:

# 构造时区: timezone(offset, name=None)
china_tz = timezone(timedelta(hours=8), 'Asia/Shanghai')
dt = datetime.now(china_tz)
print(china_tz.tzname(dt))      # Asia/Shanghai
print(china_tz.utcoffset(dt))   # 8:00:00
print(china_tz.dst(dt))         # None
print(china_tz.fromutc(dt))     # 2022-11-28 16:06:35.398835+08:00
# 属性
print(timezone.utc)         # utc 时区
print(timezone.min)         # UTC-23:59
print(timezone.max)         # UTC+23:59

4. Calendar module

This module can provide functions such as calendar printing in different formats, week setting and judgment, and leap year judgment.

4.1 Calendar object

Create a calendar object through calendar.Calendar(). The object instance can be used to: determine the day of the week, obtain the complete date of the current month, etc.

For example, to determine the day of the week:

# 0表示周一,直到6(周日)
cal = calendar.Calendar()
for wd in cal.iterweekdays():
    print(f'今天是周:{wd + 1}')

For example, to get an iterator over the full dates of the current month:

cal = calendar.Calendar()
# 打印了 2022-10-31、2022-11-01、2022-11-02 ..... 2022-12-02、2022-12-03、2022-12-04
for mds in cal.itermonthdates(2022, 11):
    print(f'{mds}')

It can also be returned in the form of a list, as follows:

cal = calendar.Calendar()
'''
以一周为列表
[datetime.date(2022, 10, 31), datetime.date(2022, 11, 1), datetime.date(2022, 11, 2), datetime.date(2022, 11, 3), datetime.date(2022, 11, 4), datetime.date(2022, 11, 5), datetime.date(2022, 11, 6)]
[datetime.date(2022, 11, 7), datetime.date(2022, 11, 8), datetime.date(2022, 11, 9), datetime.date(2022, 11, 10), datetime.date(2022, 11, 11), datetime.date(2022, 11, 12), datetime.date(2022, 11, 13)]
[datetime.date(2022, 11, 14), datetime.date(2022, 11, 15), datetime.date(2022, 11, 16), datetime.date(2022, 11, 17), datetime.date(2022, 11, 18), datetime.date(2022, 11, 19), datetime.date(2022, 11, 20)]
[datetime.date(2022, 11, 21), datetime.date(2022, 11, 22), datetime.date(2022, 11, 23), datetime.date(2022, 11, 24), datetime.date(2022, 11, 25), datetime.date(2022, 11, 26), datetime.date(2022, 11, 27)]
[datetime.date(2022, 11, 28), datetime.date(2022, 11, 29), datetime.date(2022, 11, 30), datetime.date(2022, 12, 1), datetime.date(2022, 12, 2), datetime.date(2022, 12, 3), datetime.date(2022, 12, 4)]
'''
for mdc in cal.monthdatescalendar(2022, 11):
    print(f'{mdc}')

Of course, you can also use the following API to get the date of the current month (you need to traverse the iterator to get it):

  • cal.itermonthdays(year, month): Returns an iterator for the current month.
  • cal.itermonthdays2(year, month): returns the iterator of the current month, a tuple structure, like this (28, 0).
  • cal.itermonthdays3(year, month): returns the iterator of the current month, tuple structure, similar to this (2022, 11, 28)
  • cal.itermonthdays4(year, month): returns the iterator of the current month, a tuple structure, similar to this (2022, 11, 28, 0).

You can also return a list format, and there are corresponding APIs for year and month:

cal = calendar.Calendar()
cal = calendar.Calendar()
for yd in cal.yeardatescalendar(2022):
    print(f'{yd}')
for ydc in cal.yeardayscalendar(2022):
    print(f'{ydc}')
for ydc2 in cal.yeardays2calendar(2022):
    print(f'{ydc2}')

4.2 Several Postures for Calendar Printing

<1>, generate a plain text calendar

It is necessary to construct a plain text calendar object through calendar.TextCalendar() first, and the following API can realize calendar printing:

  • formatyear(year): Print the specified annual calendar (3X4), which needs to be printed through the print() function;
  • pryear(year): Same as above, print the specified annual calendar (3X4), print directly;
  • formatmonth(year, month): print the specified monthly calendar, which needs to be printed through the print() function;
  • prmonth(year, month): Same as above, print the specified monthly calendar, directly print;

<2>, generate HTML calendar

It is necessary to construct an HTML calendar object through calendar.HTMLCalendar() first, and the following API can realize calendar printing:

  • formatyear(year): Print the specified annual calendar (composed of table labels), which needs to be printed through the print() function;
  • formatmonth(year, month): returns a year's calendar as a complete HTML page;
  • formatmonth(year, month): print the specified monthly calendar, which needs to be printed through the print() function;

<3>, other ways

Using the API directly provided by the calendar module is essentially a plain text calendar, as follows:

# 打印年份日历
print(calendar.calendar(2022))
calendar.prcal(2022)
# 打印月份日历
print(calendar.month(2022, 11))
calendar.prmonth(2022, 11)

Taking the calendar of 2022 as an example, the printed content is as follows:

                                  2022

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

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

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

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

4.3 Simple calendar text judgment

For simple calendar text, you can set the week and judge the day of the week:

# 星期,默认0为星期一,直到6(星期天)
print(f'今天是星期:{calendar.weekday(2022, 11, 28)}')  # 0
print(f'今天是星期:{calendar.firstweekday()}')  # 0
calendar.setfirstweekday(calendar.TUESDAY)  # 设置每周开始(周二)
print(f'今天是星期:{calendar.firstweekday()}')  # 1

Leap years can be determined by:

# 闰年
print(f'2022年是闰年:{calendar.isleap(2022)}')  # False
print(f'2010~2022之间是闰年的个数:{calendar.leapdays(2010, 2022)}')  # 3

You can also determine how many days there are in a specific month:

print(f'11月有多少天:{calendar.monthrange(2022, 10)[1]}')  # 30

So far, the basic knowledge about date and time and the module API have been sorted out. In actual projects, there will be time tool classes that are implemented and managed by themselves, and the basis of these tool classes is precisely these things, so they are also more important.

[Life is short, learn Python! The Python module series will be continuously updated and documented...]

Guess you like

Origin blog.csdn.net/qq_29119581/article/details/128054347