Python Route Five

Source: Internet
Author: User

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 started obsolete, changed to Time.process_time () measurement processor operation time, not including sleep time, unstable, Mac can't be measured
# print (Time.altzone) #返回与utc时间的时间差, in seconds \
# Print (Time.asctime ()) #返回时间格式 "Fri 19 11:14:16 2016",
# Print (Time.localtime ()) #返回本地时间 the struct time object format
# Print (Time.gmtime (Time.time () -800000)) #返回utc时间的struc时间对象格式

# Print (Time.asctime (Time.localtime ())) #返回时间格式 "Fri 19 11:14:16 2016",
#print (Time.ctime ()) #返回Fri 19 12:38:29 2016 format, ibid.



# Date string converted to timestamp
# string_2_struct = Time.strptime ("2016/05/22", "%y/%m/%d") #将 date string into 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时间戳转换成struct_time格式
# Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.gmtime ())) #将utc struct_time format to the specified string format

#时间加减
Import datetime

# Print (Datetime.datetime.now ()) #返回 2016-08-19 12:47:03.941925
#print (Datetime.date.fromtimestamp (Time.time ()) # Timestamp goes 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 points


#
# c_time = Datetime.datetime.now ()
# Print (C_time.replace (minute=3,hour=2)) #时间替换

Random module

#!/usr/bin/env python
#_ *_encoding:utf-8_*_
Import Random
Print (Random.random ()) #0.6445010863311293
#random. Random () is used to generate a 0 to 1 stochastic number of points: 0 <= N < 1.0
Print (Random.randint (1,7)) #4
The function prototype for the #random. Randint () is: Random.randint (A, b), which is used to generate an integer within a specified range.
# where parameter A is the lower bound, parameter B is the upper limit, the generated random number n:a <= n <= B
Print (Random.randrange (1,10)) #5
#random. Randrange's function prototype is: Random.randrange ([start], stop[, step]),
# Gets a random number in the collection that increments by the specified cardinality from within the specified range. such as: Random.randrange (10, 100, 2),
# results equal 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's a note: sequence is not a specific type in Python, but a series of types.
# list, tuple, string all belong to 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"])) #List
Print (Random.choice (("Tuple", "List", "Dict"))) #List
Print (Random.sample ([1,2,3,4,5],3)) #[1, 2, 5]
#random. Sample's function prototype is: Random.sample (sequence, k), which randomly gets a fragment of the specified length from the specified sequence. The sample function does not modify the original sequence.

Random Verification Code:

Import Random

HH = ""
For I in range (5):
h = Random.randrange (0,5)
if H = = I:
TMP = Chr (Random.randint (65,90))
Else
Tmp=random.randint (0,9)
HH +=STR (TMP)
Print (HH)
OS Module

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, equivalent to the shell CD
Os.curdir returns the current directory: ('. ')
Os.pardir Gets the parent directory string name of the current directory: (' ... ')
Os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directories
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 ') generates a single-level directory, equivalent to mkdir dirname in the shell
Os.rmdir (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir dirname
Os.listdir (' dirname ') lists all files and subdirectories in the specified directory, including hidden files, and prints as a list
Os.remove () Delete a file
Os.rename ("Oldname", "newname") renaming files/directories
Os.stat (' path/filename ') get File/directory information
OS.SEP output operating system-specific path delimiter, win under "\ \", Linux for "/"
OS.LINESEP output The line terminator used by the current platform, win under "\t\n", Linux "\ n"
OS.PATHSEP output string for splitting the file path
The Os.name output string indicates the current usage platform. Win-> ' NT '; Linux-> ' POSIX '
Os.system ("Bash command") runs a shell command that directly displays
Os.environ Getting system environment variables
Os.path.abspath (path) returns the absolute path normalized by path
Os.path.split (path) splits path into directory and file name two tuples returned
Os.path.dirname (path) returns the directory of path. is actually the first element of Os.path.split (path)
Os.path.basename (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)
Os.path.exists (path) returns true if path exists, false if path does not exist
Os.path.isabs (path) returns True if path is an absolute path
Os.path.isfile (path) returns True if path is a file that exists. otherwise returns false
Os.path.isdir (path) returns True if path is a directory that exists. otherwise returns false
Os.path.join (path1[, path2[, ...]) When multiple paths are combined, the parameters before the first absolute path are ignored
Os.path.getatime (Path) returns the last access time of the file or directory to which path is pointing
Os.path.getmtime (Path) returns the last modified time of the file or directory to which path is pointing

SYS module

SYS.ARGV command line argument list, the first element is the path of the program itself
Sys.exit (n) exit program, Exit normally (0)
Sys.version get version information for Python interpreter
Sys.maxint the largest int value
Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.platform returns the operating system platform name
Sys.stdout.write (' please: ')
val = Sys.stdin.readline () [:-1]

JSON & 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

Hashlib Module

For cryptographic related operations, the 3.x replaces the MD5 module and the SHA module, mainly providing SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm

Import HMAC
h = hmac.new (' Wueiqi ')
H.update (' Hellowo ')
Print H.hexdigest ()

Re module

‘.‘ Default match any character except \ n, if flag Dotall is specified, matches any character, including line break
The ' ^ ' matches the beginning of the character, and if you specify the flags MULTILINE, this can also be matched on (r "^a", "\nabc\neee", Flags=re. MULTILINE)
' $ ' matches the end of the character, or E.search ("foo$", "BFOO\NSDFSF", Flags=re. MULTILINE). Group () can also
' * ' matches the character before the * number 0 or more times, Re.findall ("ab*", "Cabb3abcbbac") results for [' ABB ', ' ab ', ' a ']
' + ' matches the previous character 1 or more times, Re.findall ("ab+", "Ab+cd+abb+bba") results [' AB ', ' ABB ']
‘?‘ Match a previous character 1 or 0 times
' {m} ' matches the previous character m times
' {n,m} ' matches the previous character N to M times, Re.findall ("ab{1,3}", "ABB ABC abbcbbb") Results ' ABB ', ' AB ', ' ABB ']
| Match | left or | Right character, re.search ("abc| ABC "," ABCBABCCD "). Group () result ' ABC '
' (...) ' Group match, Re.search ("(ABC) {2}A (123|456) C", "abcabca456c"). Group () Results abcabca456c


' \a ' matches only from the beginning of the character, Re.search ("\aabc", "ALEXABC") are not matched
' \z ' matches the end of the character, same as $
' \d ' matches the number 0-9
' \d ' matches non-numeric
' \w ' match [a-za-z0-9]
' \w ' matches non-[a-za-z0-9]
' s ' matches whitespace characters, \ t, \ n, \ r, Re.search ("\s+", "Ab\tc1\n3"). Group () result ' \ t '

‘(? P<name&gt, ...) ' Group Matching Re.search (? P<province>[0-9]{4}) (? P<city>[0-9]{2}) (? P&LT;BIRTHDAY&GT;[0-9]{4}) "," 371481199306143242 "). Groupdict (" city ") result {' Province ': ' 3714 ', ' City ': ' Bayi ', ' birthday ' : ' 1993 '}

The most commonly used match syntax

Re.match match from the beginning
Re.search Match contains
Re.findall all matching characters to the elements in the list to return
Re.splitall as a list separator with matched characters
Re.sub match characters and replace

Python Route Five

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.