#Learn Python # with a small hand and play with the time and date library [with source code]

Posted by sx on Mon, 03 Jan 2022 02:23:22 +0100

Python date and time

In Python, there is no native data type to support time. The operation of date and time requires the help of three modules: time, datetime and calendar.

The time module can operate the time-related functions in the C language library, and the clock time and processor running time can be obtained.
The datetime module provides a high-level interface between date and time.
Calendar module is a general calendar related function, which is used to create periodic events of weeks, months and years.

Before learning, there are some terms to add, which you can take as a convention. There are also relevant instructions in the official Python documents here, but there is a lot of information. The eraser is part of what you must know in the excerpt.

epoch is the point at which time begins, and its value depends on the platform.
For Unix, epoch is January 1, 1970 00:00:00 (UTC). To find epoch on a given platform, use time.gmtime(0) to view, for example, eraser computer display:

time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

The term era seconds refers to the total number of seconds since the epoch point in time, usually excluding leap seconds. Leap seconds are not recorded in the total number of seconds on all POSIX compliant platforms.

Programmers often call the seconds of an era a timestamp.

time module

The core of the module is to control the clock time.

get\_clock\_info function

This function obtains the basic information of the clock. The value obtained is different due to different systems. The function prototype is relatively simple:


Where name can take the following values:

  • monotonic: time.monotonic()
  • perf_counter: time.perf\_counter()
  • process_time: time.process\_time()
  • thread_time: time.thread\_time()
  • time: time.time()

The return value of this function has the following properties:

  • adjustable: returns true or False. True if the clock can be changed automatically (for example, through the NTP daemon) or manually by the system administrator; otherwise, False;
  • implementation: the name of the basic C function used to obtain the clock value, that is, the function calling the underlying C;
  • monotonic: True if the clock cannot be reversed, otherwise False;
  • Resolution: the clock resolution (float) in seconds.
import time

available_clocks = [
    ('clock', time.clock),
    ('monotonic', time.monotonic),
    ('perf_counter', time.perf_counter),
    ('process_time', time.process_time),
    ('time', time.time),

for clock_name, func in available_clocks:
        adjustable    : {info.adjustable}
        implementation: {info.implementation}
        monotonic     : {info.monotonic}
        resolution    : {info.resolution}
        current       : {current}

The operation results are shown in the figure below.

The figure above shows the eraser computer in clock and perf_ In counter, the underlying C function is the same.

Get timestamp

In Python, through time The time() function gets the number of seconds of the era, which can return the number of seconds since the beginning of epoch in floating-point format.

import time
# Output result 1615257195.558105

Timestamps are widely used to calculate time related programs, which must be mastered.

Get readable time

Timestamp is mainly used for convenient calculation of time, which is difficult for people to understand. If you want to obtain readable time, use ctime() function to obtain it.

import time
# Output: Tue Mar 9 10:35:51 2021

How to convert a timestamp to a readable time, just use the localtime function.

localtime = time.localtime(time.time())
print("Local time is :", localtime)

The output result is & lt; class 'time. struct_ time'> Type data, which will be formatted later:

Local time is : time.struct_time(tm_year=2021, tm_mon=3, tm_mday=9, tm_hour=10, tm_min=37, tm_sec=27, tm_wday=1, tm_yday=68, tm_isdst=0)

The minimum value of the timestamp in the above code is 0. The maximum value is determined by the Python environment and operating system. When I test the local 64 bit operating system, the data obtained are as follows:

import time

localtime = time.localtime(0)
print("Time is :", localtime)
# Time: time struct_ time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
localtime = time.localtime(32536799999)
print("Time is :", localtime)
# Time: time struct_ time(tm_year=3001, tm_mon=1, tm_mday=19, tm_hour=15, tm_min=59, tm_sec=59, tm_wday=0, tm_yday=19, tm_isdst=0)
localtime = time.localtime(99999999999)
print("Time is :", localtime)
# OSError: [Errno 22] Invalid argument

monotonic time

monotonic time starts timing from system startup and monotonically increases from 0.

The time of the operating system may not start from 0, and it will be recalled due to time error.

The prototype of the function is as follows. Without any parameters, it returns a floating-point number representing the value of the monotonic clock in decimal seconds:


The test code is as follows:

print("Monotonic time",time.monotonic())
# Output: monotonic time 12279.244

Processor clock time

The time() function returns the seconds of the era (timestamp), and the clock() function returns the processor clock time.
Return value of this function:

  • In the first call, the actual running time of the program is returned;
  • The call after the second time returns the time interval from the first call to this call.

    It should be noted that Python 3.8 has removed the clock() function and used time perf_ Counter() or time process_ Time() method instead.

t0 = time.clock()
# Run a piece of code
print(time.clock() - t0, "Program run time")

I use a higher version of Python, and the prompt exception is as follows:

time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead t0 = time.clock()

Performance counter time perf\_ counter

perf_ The epoch of the counter() function is undefined. Generally, this function is used for comparison and calculation, not for absolute time. Please pay attention to this point.

This function is used to measure the clock with the highest effective accuracy with a short duration, including the time consumed in the sleep state. It will be effective only after two calls.

The test code is as follows:

t0 = time.perf_counter()
# Run a piece of code
for i in range(100000):
print("Program run time", time.perf_counter() - t0)

Similar functions have perf_counter_ns(),process_time(),process_time_ns(), you can learn from the manual and master perf first_ Just use the counter() function.

Time component

The above has covered the knowledge related to time components, and the struct obtained through localtime_ Data of type time.

The functions involved here include gmtime() returning the current time in UTC, localtime() returning the time corresponding to the current time zone, and mktime() receiving struct_ Time type data and convert it to a floating-point value, that is, a timestamp.



struct\_ Contents of time type

The data format returned by the above code is:

time.struct_time(tm_year=2021, tm_mon=3, tm_mday=9, tm_hour=12, tm_min=50, tm_sec=35, tm_wday=1, tm_yday=68, tm_isdst=0)

The values can be understood according to the English meaning: tm_year (range[1,12]), tm_mon (range[1,12]), tm_mday days (range[1,31]), tm_hour days (range[0,23]), tm_min minutes (range[0,59]), tm_sec seconds (range[0,61]), tm_wday week (range[0,6], 0 is Sunday), tm_yday day of the year (range [1366] ),tm_isdst is set to 1 when daylight saving time is effective and 0 when daylight saving time is not effective. A value of - 1 indicates that this is unknown.

9.1. 8 parsing and formatting time

The strptime() and strftime() functions can make the time value in struct_ Conversion between time representation and string representation.

For the strftime function, the parameters can refer to the official.

x = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

There is no difficult point in learning here. Who can produce skillful knowledge.

Application of strptime function

x = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# Direction operation, string formatted as time struct_ time
struct_time = time.strptime(x, "%Y-%m-%d %H:%M:%S")

What you need to remember is that there are only middle characters between strftime and strptime functions. One is f and the other is p.

time section

For the time module, the sleep function is a necessary knowledge point, but it is too commonly used. You must be familiar with it.
For module learning, the most authoritative is the official manual, [time module]

datetime module

The module is much more advanced than the time module, and the time module is encapsulated to provide more powerful functions.

In the datetime module, Python provides five main object classes, as follows:

  • datetime: allows simultaneous operation of time and date;
  • Date: only operation date;
  • Time: operation time only;
  • timedelta: used for operating date and measuring time span;
  • tzinfo: process time zone.

date class

Give priority to displaying some attributes and methods of this kind, which are all knowledge at the memory level.

  • min, max: the maximum and minimum date that the date object can represent;
  • resolution: the date object represents the minimum unit of the date and returns days;
  • today(): returns the date object representing the current local date;
  • From timestamp: returns a date object according to the timestamp.

The test code is as follows:

from datetime import date
import time
print('date.min:', date.min)
print('date.max:', date.max)
print('date.resolution:', date.resolution)
print('date.today():', date.today())
print('date.fromtimestamp():', date.fromtimestamp(time.time()))

Output results:

date.min: 0001-01-01
date.max: 9999-12-31
date.resolution: 1 day, 0:00:00
date.today(): 2021-03-09
date.fromtimestamp(): 2021-03-09

Properties and methods of the date object

Create a date object with the following code:

d = date(year=2021,month=3,day=9)

The object has the following properties and methods:

  • d.year: return year;
  • d.month: return month;
  • d.day: return day;
  • d.weekday(): returns weekday, or 0 if it is Monday; If it is Tuesday, return 1, and so on;
  • d.isoweekday(): returns weekday, or 1 if it is Monday; If it is Tuesday, return 2, and so on;
  • d.isocalendar(): return format, such as (year, wk num, wk day);
  • d.isoformat(): returns a string in the format of 'YYYY-MM-DD';
  • d.strftime(fmt): custom format string, similar to strftime in the time module.

time class

Class properties defined by time class:

  • Min, Max: the minimum and maximum time that can be represented by the time class. Where, time min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
  • resolution: the smallest unit of time, here is 1 microsecond;

Through its constructor, you can create a time object.

t = time(hour=20, minute=20, second=40)

Instance methods and properties provided by the time class:

  • t.hour, t.minute, t.second, t.microsecond: hour, minute, second, microsecond;
  • t.tzinfo: time zone information;
  • t.isoformat(): return type, such as string time representation in "HH:MM:SS" format;
  • t.strftime(fmt): returns a custom format string.

datetime class

This class is a combination of date class and time class. Many properties and methods have been introduced earlier, and some commonly used properties and methods will be added.

Get current date and time:

from datetime import datetime
dt = datetime.now()

Get timestamp:

dt = datetime.now()
# Use the built-in function timestamp() of datetime
stamp = datetime.timestamp(dt)

timedelta class

Return a timedelta time interval object through the timedelta function. The function has no required parameters. If you write an integer, it means the number of days between.

# Every 10 days
# The span is 1 week

Two time interval objects can be added or subtracted from each other, and still a time interval object is returned.
If a datetime object subtracts a time interval object, the corresponding subtracted datetime object will be returned. If two datetime objects are subtracted, a time interval object will be returned.

For more information about the use of the datetime class, please refer to the [official manual].

Calendar module (calendar)

The functions of this module are calendar related, such as printing a character monthly calendar of a month.

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. You can generate pre formatted output through TextCalendar and HTMLCalendar classes.

Basic code:

import calendar

c = calendar.TextCalendar(calendar.SUNDAY)
c.prmonth(2021, 3)

The above code starts from Sunday by default, and the output result is:

     March 2021
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

The frequency of use of this module is low, and the reference address is used in detail.

Summary of this blog

This blog adds some knowledge about time and date base. I hope I can enter your favorites.

Topics: Python Back-end