Basic extension modules of Python

1. datetime module

1.1 Main modules 

datetime.date() #processing date (year, month, day) 
datetime.time() #processing time (hour, minute, second and millisecond) 
datetime.datetime() #processing date + time 
datetime.timedelta() #processing period (time interval)
#获取今天的时间
print(datetime.date.today())
print(datetime.datetime.now())

print(datetime.date.today().strftime("%Y-%m-%d %H-%M-%S"))
print(datetime.datetime.now().isoformat())

  1.2 Timestamp 

 The timestamp refers to the total number of seconds from January 01, 1970, 00:00:00 GMT to the present.

1.2.1 Converting Dates to Timestamps and Timestamps to Dates

timetuple function: convert date to struct_time format

time.mktime function: Returns a floating-point number representing the time in seconds

import datetime,time

today = datetime.date.today()
print(today.timetuple())

print(time.mktime(today.timetuple()))

print(datetime.date.fromtimestamp(1668614400.0))

1.2.2 Addition and subtraction in time 

 The timedelta() method represents the interval between two time points

import datetime
today = datetime.datetime.now()
print(today)

yesterday = today - datetime.timedelta(days=1)
print(yesterday)

hours = today - datetime.timedelta(hours=1)
print(hours)

2. Calendar module 

 Several functions and classes related to the calendar can generate a calendar in text form.

2.1 Common functions

import calendar 
calendar.calendar(<year>)        
calendar.month(<year>,<month>) #return multi-line string 
calendar.prmonth(<year>,<month>) #equivalent to print(calendar.month(< Year>,<month>)) 
calendar.prcal(<year>) #equivalent to print(calendar.calendar(<year>))
import calendar

print(calendar.month(2022,11))
print(calendar.calendar(2022))

The output shows: 

E:\ProgramData\Anaconda3\python.exe C:/Users/dl/PycharmProjects/MyProjects/1.py
   November 2022
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

                                  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

2.2 List the calendar 

calendar.monthcalendar()

Returns a calendar of a certain month in a certain year, which is a nested list. The innermost list contains seven elements representing a week (Monday to Sunday). 0 if there is no day of the month. 

import calendar

print(calendar.monthcalendar(2022,11))

输出结果:

[[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, 0, 0, 0, 0]]

 2.3 Judging leap year

calendar.isleap(<年>)
import calendar

print(calendar.isleap(2022))
print(calendar.isleap(2000))

输出结果:
False
True

  2.4 Judging the number of months and days of the week

When calculating the day of the week for a certain month, when there are a total of days, it starts from 0, Monday, Tuesday...

When calculating the day of the week, 0-6 is returned, corresponding to Monday to Sunday.

import calendar

print(calendar.monthrange(2022,11))
print(calendar.weekday(2022,11,18))

输出结果:
(1, 30)
4

Three, time module 

3.1 Get timestamp 

time.time() method

Calculate the running time of a program

import time

t1 = time.time()
a = 0
for i in range(10000):
    a += i
print(a)
t2 = time.time()
print(t2-t1)

 3.2 Get date format

3.2.1 Get the current time 

import time

t1 = time.asctime()
t2 = time.ctime()
print(t1)
print(t2)

 3.2.2 Convert tuple data to date

import time

t = (2022,11,18,11,8,30,0,0,0)
print(time.asctime(t))

输出结果:
Mon Nov 18 11:08:30 2022

 3.3 Use the index to obtain time information

import time

print(time.localtime())
t = time.localtime()
year = t[0]
print(year)

4. Arithmetic module 

  4.1 random module

 Pseudo-random number: The random function in the computer is simulated according to a certain algorithm, and the result is deterministic and predictable.

Random number seed: The random number seed is the same, and the random number sequence is also the same.

random.seed(a = None)

random() #Generate a random real number in the range [0,1)

uniform() #Generate a random floating point number within the specified range

randint(m,n) #Generate an integer within the specified range [m,n]

randrange(a,b,n) #You can randomly select a number from the set increasing by n within the range of [a,b)

getrandbits(k) #Generate k-bit binary random integers

choice() # Randomly select an element from the specified sequence

sample() #can specify the number of random elements each time

shuffle() # Randomly sort all elements in the variable sequence

import random
colors = ['red','green','blue','yellow','black']
print(random.choice(colors))
print(random.sample(colors,3))
random.shuffle(colors)
print(colors)

输出结果:
black
['black', 'blue', 'green']
['red', 'blue', 'green', 'yellow', 'black']

5. File text reading and writing module 

5.1 Opening of files

open() function:

f = open(filename[,mode[,buffering]])

f: the file object returned by open()

filename: the string name of the file

mode: optional parameter, open mode and file type 

buffering: optional parameter, the buffer of the file, the default is -1

Open mode of the file:

The first letter of mode indicates the operation on it:

'r': indicates read mode

'w': Indicates write mode

'x': Indicates that the file is newly created and written if the file does not exist

'a': Indicates that the content is appended at the end of the file

'+': Indicates read and write mode

The second letter of mode is the file type:

't': Indicates text type

'b': indicates a binary file

5.2 Reading, writing and accessing files 

File write operations:

f.write(str)

f.writelines(strlist): write a list of strings

File read operation:

 f.read()

f.readline(): returns a line

f.readlines(): return all lines, list

f = open('mytxt','w')
f.writelines(['apple\n','orange\n'])
f.close()
f = open('mytxt','r')
print(f.readlines())
f.close()

 After opening the file, you must remember to close it. The function of closing is to terminate the connection to the external file and refresh the data in the cache area to the hard disk at the same time.

5.3 Structured text files: CSV 

File reading—reader

re = csv.reader()

Accepts an iterable object (such as a csv file) and returns a generator from which the content can be parsed.

File reading—DictReader

 Similar to the reader, it is suitable for csv files with headers, and each returned cell is placed in a tuple value.

File write operation:
w = csv.writer()

w.writerow(rows)

When the file does not exist, it is automatically generated, supporting single-line writing and multi-line writing

Dictionary data is written:

w = csv.DictWriter()

w.writeheader()

w.writerow(rows)

Guess you like

Origin blog.csdn.net/m0_51769031/article/details/127900008