And a time module datetime
1.1 time module
import time
Priority grasp
# Timestamp timestamp: from 1970 to the present number of seconds elapsed effect: the time interval for calculating Print (the time.time ()) # according to a certain display time format Format String: 2020-03-30 11:11 : 11 AM effect: a presentation time Print (the time.strftime ( ' % Y-M-% D%% H:% M:% S% P ' )) # structured time, action: to obtain separate a certain part of the time. Structured time (struct_time) tuple total of nine elements were nine elements :( year, month, day, hour, minute, second, the first few weeks of the year, day of the year, daylight saving time) RES = Print (time.localtime ()) Print (RES) Print (res.tm_year) # sleep (pause) Print (the time.sleep (3))
Need to know
# Conversion time format # struct_time-> timestamp S_TIME = time.localtime () Print (time.mktime (S_TIME)) # the mktime (T): The conversion of a struct_time timestamp. # Timestamp -> struct_time tp_time = the time.time () Print (time.localtime (tp_time))
Part of the master
# The strftime formatted time string into S_TIME = time.localtime () Print (The time.strftime ( ' % Y-M-% D%% H:% M:% S ' , S_TIME)) # to a formatted time string into struct_time. In fact it strftime () is the inverse operation. Print (the time.strptime ( ' 2020-03-30 16:16:38 ' , ' % Y-M-% D%% H:% M:% S ' )) # !!! really need to know only one: String the format <------> timestamp # the format String ---> struct_time ---> timestamp struct_time the time.strptime = ( ' 1988-03-03 11:11:11 ' , ' %% Y-M- D% H%:% M:% S 'time.mktime(struct_time) print(timestamp) # format string<---struct_time<---timestamp res=time.strftime('%Y-%m-%d %X',time.localtime()) print(res)
Added: Coordinated Universal Time and local time
Print (time.localtime ()) Print (time.gmtime ()) # Universal Time to learn
To understanding
Print (that time.asctime ()) # to a timestamp (in seconds calculated in floating point) is converted to that time.asctime () form. If the parameter is not given or when #None, it will default time.time () as a parameter. It acts time.asctime (time.localtime (secs)).
1.2 datetime
Import datetime Print (datetime.date.fromtimestamp (the time.time ())) # stamp date format directly converted into Print (datetime.datetime.now ()) # current time Print (datetime.datetime.now () + datetime. timedelta (days =. 3)) # current time plus 3 days Print (datetime.datetime.now () + the datetime.timedelta (= weeks. 1)) # current time plus one week Print (datetime.datetime.utcnow ()) # time time c_time = datetime.datetime.now () Print (c_time.replace (=. 3 minute, hour = 2)) # time Shift
Two random module
Import Random Print (random.random ()) # (0,1) is greater than 0 and less than a float ---- decimal between 1 Print (the random.randint (l, 3)) # [l, 3] is greater than or equal to 1 and less than or equal to integer. 3 Print (random.randrange (l, 3)) # [l, 3) is greater than 1 and less than or equal to an integer between. 3 Print (the random.choice ([111, ' AAA ' , [1 2]])) # randomly selected element in a Print (random.sample ([111, ' ZZ ' , [1,2]]), 2) # list elements in any combination of two Print (random.uniform (. 1 , 3)) # is greater than a decimal less than 3, such as 1.927109612082716 Item = [1, 3,. 5,. 7,. 9 ] random.shuffle (item) # Scramble item, equivalent to "shuffle" Print (item)
Case verification code
import random def make_code(size=4): res = '' for i in range(size): s1 = chr(random.randint(65,90)) s2 = str(random.randint(0,9)) res+=random.choice([s1,s2]) return res print(make_code(6))
Three os module
Print (os.listdir ( ' . ' ) # get all the subfolders and name the subfolder of a certain folder Print (os.path.getsize ( ' . ' )) # return path size os.remove () # delete a file os.rename ( " oldname " , " newname " ) # rename a file / directory os.system (the command) # convert a string into a command in a terminal run Print (os.environ) # get the system environment variables os .environ [ ' AAAAAAAAAA ' ] = ' 111 ' #Provisions: key value must be a string and Print (os.environ) Print (os.path.dirname (R & lt ' /a/b/c/d.txt ' )) # Returns the directory path Print (the os.path. basename (r ' /a/b/c/d.txt ' )) # returns the path of the last file name Print (os.path.isfile (path)) # If the path is an existing file and returns True. False otherwise be used to determine whether the document Print (os.path.isdir (path)) # If the path is an existing directory, then True is returned. Otherwise False Print (the os.path.join ( ' A ' , ' / ' , ' B ' , 'C ' , ' D ' )) # returns after combining a plurality of paths, parameters before the first absolute path (/) will be ignored
Print (The os.getcwd ()) # Get the current working directory, i.e., the current working directory path python script Print (the os.chdir ( " dirname " )) # change the current working directory script; corresponding to the CD the shell os.makdirs ( ' dirname1 / dirname2 ' ) # can generate multilayer recursive directory os.removedirs ( ' dirname1 ' ) # If the directory is empty, delete, and recursively to the parent directory, should be empty, delete, and so on os. mkdir ( ' dirname ' ) # generate a single level directory; is equivalent to the shell dirname mkdir os.rmdir ( ' dirname ' ) # delete a single stage empty directory, if the directory is not empty can not be deleted, being given; the equivalent of the shell rmdir dirname the os.stat ( ' path / filename ' ) # get the file / directory information os.sep # output operation system-specific path separator is "\\" lower win, Linux, the "/" os.linesep # output current platform using line terminator, to win the next "\ t \ n", as "\ n" under Linux os.pathsep # at output a win string file path is divided;, under Linux is: the os.name # output use string to indicate the current platform. win -> 'NT'; the Linux -> 'POSIX' os.path.abspath with (path) # return path normalized absolute path The os.path.split (path) # divided into path and filename directory tuple returned os .path.split (path) # the second element os.path.exists (path) # If the path exists, returns True; if the path does not exist, returns False the os.path. If the path is an absolute path, returns True os.path.getatime (path) # Returns the last access time of the file or directory path pointed os.path.getmtime (path) # Returns the last modified path points to a file or directory time
Processing path ways os
# Way: I recommend this base_dir = os.path.dirname (os.path.dirname ( __FILE__ )) Print (base_dir) # Second way base_dir = os.path.normpath (the os.path.join ( __FILE__ , ' . . ' , ' .. ' )) Print (base_dir) # mode # after three python3.5, the introduction of a new module pathlib from pathlib Import the path RES = the path ( __FILE__ ) .parent.parent Print (RES) # path splicing RES = the Path ( ' / a / B / C ' ) /'d/e.txt' print(res) print(res.resolve())
Four sys module
sys.argv # command line arguments List, the first element of the program itself is the path sys.exit (the n-) # exit the program, when the normal exit Exit (0) sys.version # get Python interpreter version information sys.maxint # maximum Int value of sys.path # return the module search path, use the PYTHONPATH environment variable initialization value sys.platform # returns the operating system platform name
Print progress bar case
import sys import time def progress(percent,width=50): if percent>1: percent=1 show_str = ('[%%-%ds]'%width)%(int(percent*width)*'*') print('\r%s %s%%'%(show_str,int(percent*100)),end='') data_size=10250 recv_size=0 while recv_size < data_size: time.sleep(0.1) #模拟数据的传输延迟 + = 1024 recv_size # each received 1024 Percent = recv_size / Data_Size # ratio received Progress (Percent, width = 70) # progress bar width 70