Python Development Foundation DAY11 Module 1

Source: Internet
Author: User
Tags sha1 shuffle python script

Time Module

In Python, there are usually three ways to represent time: timestamp, tuple (struct_time), formatted time string:

(1) 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.

(2) formatted time string (format string): ' 1988-03-16 '

(3) tuple (struct_time): Struct_time A total of 9 elements total nine elements: (year, month, day, time, minute, second, week of the year, Day of the year, etc.)

1 # <1> timestamp 2 >>> import time 3 >>> time.time ()      #--------------Returns the timestamp of the current time 4 1493136727.099066  #距离1970年1月1日00:00:00 There are so many seconds 5  6 # <2> time string 7 >>> time.strftime ("%y-%m-%d%x") 8 ' 2017-04-26 00:32:18 ' 9 # <3> Time tuple >>> time.localtime () time.struct_time (tm_year=2017, tm_mon=4, tm_mday=26,13                  tm_ Hour=0, tm_min=32, tm_sec=42, tm_wday=2,14                  tm_yday=116, tm_isdst=0)

Time Conversion Method:

1 print (Time.localtime ())  #时间对象, the object's data type must be available through this object. Operation of the Method 2 S=time.localtime ()     #结构化时间对象, with timestamp as parameter 3 print ( s.tm_year)    #返回年份4 print (Time.gmtime ())    #世家标准时间, and time zone related, also with timestamp 5 print (Time.mktime (Time.localtime ()))    # The method of transforming structured time into time stamp

1 Print (Time.asctime (Time.localtime ()))    #自动格式化当前时间2 print (Time.ctime (15352345134))    #自动格式化当前时间

Manual format Time:

Print (Time.strftime ('%y-%m-%d ', Time.localtime ()))   #结构化时间转化成字符串, split symbol-can be replaced arbitrarily, can be any character print (Time.strptime (" 2017-03-16 ","%y-%m-%d "))    #结构化时间转换成时间戳

Summary: Time stamp is the time that the computer can recognize; The time string is the time that a person can read; Tuples are used to manipulate time.

Other methods:

1 Time.sleep (3)    #睡眠3秒 for deferred code execution

Random module

Random number module, capable of simulating random numbers using the corresponding algorithm according to the instruction

1 >>> Import Random 2 >>> random.random ()      # greater than 0 and less than 1 decimal places 3 0.7664338663654585 4  5 >>> R Andom.randint (1,5)  # Integer greater than or equal to 1 and less than or equal to 5 6 2 7  8 >>> Random.randrange (1,3) # is greater than or equal to 1 and is less than 3 integer 9, >> ;> Random.choice ([1, ' 23°c ', [4,5]])  # #1或者23或者 [4,5]12 113 >>> Random.sample ([1, ' 23 ', [4,5]],2) # # List elements any of 2 combinations [[4, 5], ']16 >>> random.uniform (1,3) #大于1小于3的小数18 1.627014718053383819 >>> item= [1,3,5,7,9]21 >>> Random.shuffle (item) # Break order (ITEM23) [5, 1, 3, 7, 9]24 >>> random.shuffle (item) >>> ITEM26 [5, 9, 7, 1, 3]

Examples of applications:

1 Import Random 2  3 def v_code (): 4     code = ' 5 for     I in range (5): 6         num=random.randint (0,9) 7         ALF=CHR (Random.randint (65,90)) 8         Add=random.choice ([num,alf]) 9         code= "". Join ([Code,str (add)])     return Code11 print (V_code ())

Hashlib Module

Python's hashlib provides a common digest algorithm, such as MD5,SHA1 and so on.

What is a digest algorithm? Abstract the algorithm is also called hash algorithm and hashing algorithm. It uses a function to convert any length of data into a fixed length data string (usually represented by a 16-binary string). It is very difficult to use the hash algorithm to reverse the source data, so generally speaking, we think that the value of hash is an irreversible operation.

MD5 calculation:

1 Import hashlib2 MD5 = HASHLIB.MD5 () 3 md5.update (' How to use MD5 in Python hashlib? ') 4 Print Md5.hexdigest () 5 6 The results are as follows: 7 d26a53750bc40b38b65a520292f69306

If you have a large amount of data, you can call Update () multiple times in chunks, and the result is the same:

1 MD5 = HASHLIB.MD5 () 2 md5.update (' How to use MD5 in ') 3 md5.update (' Python hashlib? ') 4 Print md5.hexdigest ()

MD5 is the most common digest algorithm and is fast enough to generate a fixed byte of bytes, typically represented by a 32-bit 16 binary string. Another common digest algorithm is SHA1, which calls SHA1 and calls MD5 exactly like:

1 Import hashlib2 SHA1 = HASHLIB.SHA1 () 3 sha1.update (' How to use SHA1 in ') 4 sha1.update (' Python hashlib? ') 5 Print sha1.hexdigest ()

The result of the SHA1 is a bit byte, which is usually represented by a 40-bit 16 binary string. Algorithms that are more secure than SHA1 are SHA256 and SHA512, but the more secure the algorithm is, the slower it is, and the longer the digest length.

OS Module

An OS module is an interface that interacts with the operating system

 1 os.getcwd () Gets the current working directory, which is the directory path of the current Python script work 2 os.chdir ("DirName") changes the current script working directory, equivalent to the shell under CD 3 Os.curdir returns the current directory: ('. ') 4 OS.P Ardir Gets the parent directory string name of the current directory: (' ... ') 5 os.makedirs ('. ') can generate a multi-level recursive directory 6 os.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to The first level of the directory, if also empty, then delete, and so on 7 os.mkdir (' dirname ') to generate a single-level directory, equivalent to the shell mkdir dirname 8 os.rmdir (' dirname ') delete a single-level empty directory, if the directory is not empty can not be deleted, reported The equivalent of the shell rmdir dirname 9 os.listdir (' dirname ') lists all files and subdirectories under the specified directory, including hidden files, and prints a list of os.remove () deletes a file Os.rename ("O Ldname "," newname ") Rename File/directory Os.stat (' path/filename ') get File/directory information OS.SEP output operating system-specific path delimiter, win under" \ \ ", Linux under"/"OS.L INESEP output The line terminator used by the current platform, win under "\t\n", Linux under "\ n" os.pathsep output is used to split the file path of the string win under, Linux: The Os.name output string indicates the current use of the platform. Win-> ' NT ';  Linux-> ' POSIX ' Os.system ("Bash command") runs a shell command that directly displays the Os.environ acquisition system environment variable Os.path.abspath (PATH) Returns path normalized absolute path Os.path.split (path) divides path into directory and file name two tuples return Os.path.dirname (path) to the directory where path is returned. is actually the first element of Os.path.split (path) os.path.basename (path) returns the file name of the last 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, or False24 os.path.isabs (path) If path does not exist If path is an absolute path, return True25 os.path.isfile (path) If path is an existing file, return true. Otherwise, return False26 Os.path.isdir (path) True if path is a directory that exists.  Otherwise return False27 Os.path.join (path1[, path2[, ...])  When multiple paths are combined and returned, 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 pointed to by Path Os.path.getsize (path) returns the size of path

Python Development Foundation DAY11 Module 1

Related Article

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.