Python advanced "11th" module (bottom) of the common module

Source: Internet
Author: User
Tags serialization shuffle

The built-in module is a Python-enabled feature that requires "import" and "use" when using the corresponding functions of the built-in modules.

One, Time module

In Python, there are usually several ways to represent 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.
    • Formatted time string (format string)
    • Structured time (Struct_time): Struct_time A total of 9 elements in total nine elements: (year, month, day, hour, minute, second, week of the year, Day of the year, summer Time)
Import time#--------------------------We start with the current time, so that we can quickly understand three forms of time print (Time.time ()) # Timestamp: 1487130156.419527print ( Time.strftime ("%y-%m-%d%x") #格式化的时间字符串: ' 2017-02-15 11:40:53 ' Print (Time.localtime ()) #本地时区的struct_timeprint ( Time.gmtime ())    #UTC时区的struct_time

#--------------------------in Figure 1 conversion time # localtime ([secs]) # Converts a timestamp to the struct_time of the current time zone. The secs parameter is not provided, whichever is the current time. Time.localtime () Time.localtime (1473525444.037215) # gmtime ([secs]) and localtime () method similar to Gmtime () The Struct_time method is to convert a timestamp to the UTC time zone (0 o'clock Zone). # mktime (t): Converts a struct_time to a timestamp. Print (Time.mktime (Time.localtime ())) #1473525749.0# strftime (format[, T]): A tuple representing time or struct_ Time, such as returned by Time.localtime () and # Time.gmtime (), is converted to a formatted date string. If T is not specified, the Time.localtime () is passed in. If any of the # elements in the tuple are out of bounds, the ValueError error will be thrown. Print (Time.strftime ("%y-%m-%d%x", Time.localtime ())) #2016 -09-11 00:49:56# time.strptime (string[, format]) # Converts a formatted time string to Struct_time. In fact it is inverse operation with strftime (). Print (Time.strptime (' 2011-05-05 16:37:06 ', '%y-%m-%d%x ')) #time. Struct_time (tm_year=2011, tm_mon=5, tm_mday=5, tm_ Hour=16, tm_min=37, tm_sec=6,#  tm_wday=3, tm_yday=125, tm_isdst=-1) #在这个函数中, format defaults to: "%a%b%d%h:%m:%s%Y".

 

#--------------------------2 Conversion Time # asctime ([t]): A tuple or struct_time representing time is represented in this form: ' Sun June 20 23:21:05 1993 '. # If there are no arguments, time.localtime () will be passed in as a parameter. Print (Time.asctime ()) #Sun Sep one 00:43:43 2016# ctime ([secs]): Converts a timestamp (floating point number in seconds) to the form of Time.asctime (). If the parameter is not given or is # None, the default Time.time () is the parameter. Its function is equivalent to Time.asctime (time.localtime (secs)). Print (Time.ctime ())  # Sun Sep 00:46:38 2016print (time.ctime (Time.time ()))  # Sun Sep 11 00:46:38 2016

Second, random module

Import random Print (Random.random ()) # (0,1)----float    greater than 0 and less than 1 decimal between print (Random.randint (1,3))  #[1,3]    integers greater than or equal to 1 and less than or equal to 3 print (Random.randrange (1,3)) #[1,3)    is greater than or equal to 1 and is less than 3 integer print (Random.choice ([1, ' 23 ', [4,5]])) # 1 or 23 or [4,5] print (Random.sample ([1, ' ", [4,5]],2)]) #列表元素任意2个组合 print (Random.uniform (1,3)) #大于1小于3的小数, such as 1.927109612082716   item=[1,3,5,7,9]random.shuffle (item) #打乱item的顺序, equivalent to "Shuffle" print (item)

Third, OS module and SYS module

An OS module is an interface that interacts with the operating system to provide system-level operations.

The SYS module is used to provide actions related to the Python interpreter.

Iv. serialization

Two modules for serialization in Python

    • JSON is used to convert between "string" and "Python Basic data Types"
    • Pickle for "Python-specific type" and "Python basic data type" to convert between

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

1.json Module

If we are going to pass objects between different programming languages, we have to serialize the object into a standard format, such as XML, but the better way is to serialize it to JSON, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a network. JSON is not only a standard format, but also faster than XML, and can be read directly in the Web page, very convenient.

The object that JSON represents is the standard JavaScript language object.

Precautions:

Import json#dct= "{' 1 ': 111}" #json do not recognize single quotes #dct=str ({"1": 111}) #报错 because the generated data is still single quotes: {' One ': ' 1}dct= ' {"1": "111"} ' Print ( Json.loads (DCT)) #conclusion: #        No matter how the data is created, as long as the JSON format is satisfied, it can be json.loads out, not necessarily dumps data to loads
#----------------------------serialized import JSON dic={' name ': ' Alvin ', ' age ': at $, ' sex ': ' Male '}print (type (DIC)) #<class ' Dict ' > J=json.dumps (DIC) print (Type (j)) #<class ' str ' >  f=open (' serialized object ', ' W ') F.write (j)  #---------- ---------equivalent to Json.dump (dic,f) f.close () #-----------------------------deserialization <br>import jsonf=open (' serialized object ') data =json.loads (F.read ()) #  equivalent to Data=json.load (f)

2.pickle Module

# #----------------------------serialized import Pickle dic={' name ': ' Alvin ', ' age ': at $, ' sex ': ' Male '} print (Type (DIC)) #< Class ' Dict ' > J=pickle.dumps (DIC) print (Type (j)) #<class ' bytes ' >  f=open (' serialized object _pickle ', ' WB ') # Note is that W is written STR,WB is written bytes,j is ' bytes ' F.write (j)  #-------------------equivalent to Pickle.dump (dic,f) f.close () #------------- ------------deserialization of Import Picklef=open (' serialized object _pickle ', ' RB ') Data=pickle.loads (F.read ()) #  equivalent to Data=pickle.load (f)  Print (data[' age ')    

The problem with Pickle is the same as for all other programming language-specific serialization problems, that is, it can only be used in Python, and may be incompatible with each other in Python, so it's okay to save only those unimportant data with pickle and not successfully deserialize it.

Five, re module

Python advanced "11th" module (bottom) of the common module

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.