One: built-in Modules
Time and DateTime
In python, there are usually several ways to represent time: 1) timestamp 2) formatted time string 3) tuples (struct_time) A total of nine elements. Because Python's time module implementation primarily calls the C library, each platform may be different.
UTC (coordinated Universal time, World Co-ordination) is gmt, world standard Time. In China for utc+8. DST (daylight Saving Time) is daylight saving Time.
Timestamp (timestamp): typically, A timestamp represents an offset that is calculated in seconds, starting January 1, 1970 00:00:00. We run "type (time.time ())" and return the float type. The function that returns the Timestamp method mainly has time (), clock () and so On.
Tuple (struct_time) mode: There are 9 elements in the Struct_time tuple, and the functions that return struct_time are mainly gmtime (), localtime (), strptime (). Several elements in this way tuple are listed Below:
#_ *_coding:utf-8_*_import time# print (time.clock ()) #返回处理器时间, 3.3 obsolete , Changed to Time.process_time () measurement processor time, not including sleep time, unstable, mac on the test # print (time.altzone) #返回与utc时间的时间差, In seconds # print (time.asctime ()) #返回时间格式 "fri aug 19 11:14:16 2016", # print ( Time.localtime ()) #返回本地时间 struct time Object Format # print (time.gmtime (time.time () -800000)) # Returns the Struc time Object format for UTC time # print (time.asctime (time.localtime ())) #返回时间格式 "fri aug 19 11:14:16 2016 ", #print (time.ctime ()) #返回Fri Aug 19 12:38:29 2016 format, ibid. # Date string goto timestamp # string_2_struct = time.strptime ("2016/05/22", "%y/%m/%d") #将 Date string Convert to struct time object format # print (string_2_struct) # ## struct_2_stamp = time.mktime (string_2_struct) #将struct时间对象转成时间戳 # print (struct_2_stamp) #将时间戳转为字符串格式 # print ( Time.gmtime (time.time () -86640)) #将utC Timestamp converted to struct_time format # print (time.strftime ("%y-%m-%d %h:%m:%s", time.gmtime ()) ) #将utc Struct_time format is converted to the specified string format # time plus minus import datetime# print (datetime.datetime.now ()) #返回 2016-08-19 12:47:03.941925#print (datetime.date.fromtimestamp (time.time ()) ) # timestamp go directly to date format 2016-08-19# print (datetime.datetime.now () ) # print (datetime.datetime.now () + Datetime.timedelta (3)) #当前时间 + 3 days # print (datetime.datetime.now () + datetime.timedelta (-3)) #当前时间-3 days # print (datetime.datetime.now () + datetime.timedelta (hours=3)) #当前时间 + 3 hours # print (datetime.datetime.now () + datetime.timedelta (minutes=30)) #当前时间 +30 min ## c_time = datetime.datetime.now () # print (c_time.replace (minute=3,hour=2)) #时间替换
Formatting references
%a Local (locale) Simplified week name %A Local full week name %b Local Simplified month name %B Local full month name %c Local appropriate date and time representation %d The day of the one month (01 - 31) %H the hour of the week (24-hour, 00 - 23) %I hours (12 hour system, 01 - 12) %j Day of the year (001 - 366) %m Month (01 - 12) %M minutes (00 - 59) %p local AM or pm's corresponding character one %S sec (01 - 61) two %U The number of weeks in a year. (00 - 53 WeekThe day is the beginning of one weeks. All days before the first Sunday are placed in the No. 0 week. three %w one days of the week (0 - 6,0 is Sunday) three %W and%u are basically the same, the difference Is%W with Monday for one weeks to Start. %x Local appropriate dates %X Local time %y year of the century (00 - 99) %y full year %Z time zone name (if no null character exists) %% '% ' character
Time Relationship Transformation
650) this.width=650; "title=" time3.jpg "alt=" wkiol1e28cpblygaaaglkn2vq_c463.jpg-wh_50 "src=" http://s2.51cto.com/ Wyfs02/m01/86/2f/wkiol1e28cpblygaaaglkn2vq_c463.jpg-wh_500x0-wm_3-wmp_4-s_1879023494.jpg "/>
More Click here
2.random Module
#!/usr/bin/env python#_*_encoding: utf-8_*_import randomprint (random.random ()) #0 .6445010863311293 #random. random () is used to generate a 0 to 1 random character point: 0 <= n < The function prototype for 1.0print (random.randint (1,7)) #4 #random.randint () is: random.randint (a, b), which is used to generate integers in a specified range. # where parameter A is the lower bound, parameter B is the upper bound, and the generated random number n: a <= n <= bprint (random.randrange (1,10)) #5 #random.randrange's function prototype Is: Random.randrange ([start], stop[, step]),# from the specified range, in the collection incremented by the specified cardinality Gets a random number. Such as: random.randrange (10, 100, 2),# result is equivalent to from [10, 12, 14, 16, ... 96, 98] gets a random number in the Sequence. # random.randrange (10, 100, 2) is equivalent to random.choice (range (10, 100, 2) on the Result. Print (random.choice (' liukuni ')) #i #random.choice gets a random element from the Sequence. # its function prototype is: Random.choice (sequence). The parameter sequence represents an ordered Type. # here to Illustrate: sequence is not a specific type in python, but a series of types. # list, tuple, strings are all part of sequence。 For sequence, You can view the Python manual data Model Chapter. # Here are some examples of using choice: print (random.choice ("learning python")) #学print (random.choice (["jgood", "is", "a", "handsome", " Boy "])) #Listprint (random.choice ((" Tuple "," List "," Dict ")) #Listprint ( Random.sample ([1,2,3,4,5],3)) #[1, 2, 5] #random. sample's function prototype Is: random.sample ( sequence, k), a fragment of the specified length is randomly obtained from the specified sequence. The sample function does not modify the original sequence.
Practical application:
#!/usr/bin/env python# encoding: utf-8import randomimport string# random integer: print ( random.randint (0,99)) #70 # Randomly Select an even number between 0 and 100: print ( Random.randrange (0, 101, 2)) #4 # random floating point number: print ( random.random ()) # 0.2746445568079129print (random.uniform (1, 10)) #9.887001463194844# random character: print (random.choice (' ABCDEFG &#%^*f ') #f # Select a specific number of characters in more than one character: print (random.sample (' abcdefghij ', 3)) #[' f ', ' h ', ' d ']# Randomly selected string: print ( random.choice [' apple ', ' pear ', ' peach ', ' orange ', ' lemon ' ] )) #apple # shuffle #items = [1,2,3,4,5,6,7]print (items) #[1, 2, 3, 4, 5, 6, 7]random.shuffle (items) Print (items) #[1, 4, 7, 2, 5, 3, 6]
Generate Random Verification code:
Import Randomcheckcode = ' For I in range (4): current = Random.randrange (0,4) if current! = i:temp = Chr (ran Dom.randint (65,90)) else:temp = random.randint (0,9) Checkcode + = str (temp) print (checkcode)
3.os Module
Provides an interface to invoke the operating system
OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work Os.chdir ("dirname") changes the current script working directory, which is equivalent to the shell Cdos.curdir return current directory: ('. ') os.pardir Gets the parent directory string name of the current directory: (' ... ') Os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directory os.removedirs (' dirname1 ') If the directory is empty, then delete, and recursively to the previous level of the directory, if also empty, then delete, and so on Os.mkdir (' dirname ') generate a single-level directory, equivalent to the shell mkdir Dirnameos.rmdir (' dirname ') Delete single-level empty directory, If the directory is not empty can not be deleted, error; equivalent to Rmdir dirnameos.listdir in the shell (' dirname ') list all files and subdirectories under the specified directory, including hidden files, and print os.remove () Delete a file os.rename (" Oldname "," newname ") rename file/directory os.stat (' path/filename ') get file/directory information os.sep Output operating system-specific path delimiter, win under "\ \", Linux for "/" os.linesep output the current platform using the line terminator, win under "\t\n", Linux "\ n "os.pathsep output string to split file path os.name output string indicates the current usage platform. Win-> ' nt '; linux-> ' POSIX ' Os.system ("bash command") Run shell command, directly display os.environ get system environment variable Os.path.abspath (path) return path normalized absolute path Os.path.split ( Path) partition path into directory and file name two tuples return os.path.dirname (path) directory to return path. It is actually the first element of Os.path.split (path) returns the last file name of Path. If path ends with a/or \, then a null value is Returned. The second element of Os.path.split (path) returns True if Path exists, or Falseos.path.isabs (path) if path does not exist. If path is an absolute path, return Trueos.path.isfile (path) True if path is an existing File. otherwise, return Falseos.path.isdir (path) True if path is an existing directory. Otherwise return Falseos.path.join (path1[, path2[, ...]) returns a combination of multiple paths, the parameters before the first absolute path are ignored Os.path.getatime (path) Returns the last access time of the file or directory pointed to by path Os.path.getmtime (path) returns the last modified time of the file or directory to which path is pointing
More Click here
4.sys Module
SYS.ARGV command line argument list, The first element is the program itself path Sys.exit (n) exits the program, exit normally exits (0) Sys.version gets the version information of the Python interpreter sys.maxin t the largest int value Sys.path returns the search path for the module, initialized with the value of the PYTHONPATH environment variable Sys.platform returns the operating system platform name Sys.stdout.write (' please: ') val = sys.stdin.readline () [:-1]
5.shutil Module
Reference http://www.cnblogs.com/wupeiqi/articles/4963027.html
6.json and Pickle Modules
Two modules for serialization
json, used to convert between string and Python data types
Pickle for conversion between python-specific types and Python data types
The JSON module provides four functions: dumps, dump, loads, Load
The Pickle module provides four functions: dumps, dump, loads, Load
650) this.width=650; "title=" json.png "alt=" wkiol1e29dbjpr--aabupcnkhv0613.png-wh_50 "src=" http://s2.51cto.com/ Wyfs02/m02/86/2f/wkiol1e29dbjpr--aabupcnkhv0613.png-wh_500x0-wm_3-wmp_4-s_2976219011.png "/>
7. Shelve Module
The shelve module is a simple k,v module that persists memory data through a file and can persist any Python data format that pickle can support
Import shelve d = Shelve.open (' shelve_test ') #打开一个文件 class Test (object): def __init__ (self,n): SELF.N = N T = Test (123) t2 = Test (123334) name = ["alex", "rain", "test"] d["test"] = name #持久化列表d ["t1"] = t #持久化类d ["t2"] = T2 D.clo Se ()
This article is from "a good person" blog, Please be sure to keep this source http://egon09.blog.51cto.com/9161406/1840425
Python module Part3