The Python module time,

Source: Internet
Author: User
Tags format definition local time month name parent directory serialization shuffle python script

Time Module

When it comes to time, we need to use the time module. Before using the module, you should first import the module.

# Common Methods 1. Time.sleep (secs) (thread) Delays the specified time run. Unit is seconds. 2. Time.time () Gets the current timestamp

Three ways to represent time

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): ' 1999-12-06 '

%y Two-digit year representation (00-99)%Y Four-digit year representation (000-9999)%m Month (01-12)One day in%d months (0-31)%H 24-hour hours (0-23)%I 12-hour hours (01-12)%M minutes (00=59)%s seconds (00-59)%a local simplified week name%A Local Full week name%b Local simplified month name%B Local Full month name%c Local corresponding date representation and time representation%j Day of the Year (001-366)%p equivalent of local a.m. or P.M.%u days of the year (00-53) Sunday for the beginning of the week%w Week (0-6), Sunday for the beginning of the week%W number of weeks in the year (00-53) Monday for the beginning of the week%x Local corresponding date representation%X Local corresponding time representation%Z name of the current time zonePercent% of the number itself
python format symbols in time Date:

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

First, let's start by importing the time module to recognize the several formats in Python that represent times:

#Import Time Module>>>Import Time#time Stamp>>>time.time ()1500875844.800804#Time String>>>time.strftime ("%y-%m-%d%x")'2017-07-24 13:54:37'>>>time.strftime ("%y-%m-%d%h-%m-%s")'2017-07-24 13-55-04'#time tuple: localtime converts a timestamp to the struct_time of the current time zonetime.localtime () time.struct_time (Tm_year=2017, tm_mon=7, tm_mday=24, Tm_hour=13, tm_min=59, tm_sec=37, Tm_wday=0, tm_yday=205, tm_isdst=0)

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.

Conversions between several formats

#Timestamp-- structured time#time.gmtime (timestamp) #UTC时间, consistent with local time in London, UK#time.localtime (timestamp) #当地时间. For example, we are now implementing this method in Beijing: 8 hour difference from UTC time, UTC time + 8 hour = Beijing Time>>>time.gmtime (1500000000) time.struct_time (tm_year=2017, Tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)>>>time.localtime (1500000000) time.struct_time (tm_year=2017, Tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)#structured time-time stamping#Time.mktime (structured time)>>>time_tuple = Time.localtime (1500000000)>>>time.mktime (time_tuple)1500000000.0
#structured Time--string time#time.strftime ("format definition", "structured Time") if the structured time parameter does not pass, the actual current time>>>time.strftime ("%y-%m-%d%x")'2017-07-24 14:55:36'>>>time.strftime ("%y-%m-%d", Time.localtime (1500000000))'2017-07-14'#string Time--structured time#Time.strptime (Time string, string corresponding format)>>>time.strptime ("2017-03-16","%y-%m-%d") time.struct_time (tm_year=2017, Tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, Tm_isdst=-1)>>>time.strptime ("07/24/2017","%m/%d/%y") time.struct_time (tm_year=2017, Tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, Tm_isdst=-1)

#structured Time--%a%b%d%h:%m:%s%y string#Time.asctime (structured time) if the parameter is not passed, the format string of the current time is returned directly>>>time.asctime (Time.localtime (1500000000))'Fri Jul 10:40:00'>>>time.asctime ()'Mon Jul 15:18:33'#Timestamp- %a%d%d%h:%m:%s%y string#Time.ctime (timestamp) If the parameter is not passed, the format string of the current time is returned directly>>>time.ctime ()'Mon Jul 15:19:07'>>>time.ctime (1500000000)'Fri Jul 10:40:00' 
ImportTimetrue_time=time.mktime (Time.strptime ('2017-09-11 08:30:00','%y-%m-%d%h:%m:%s')) Time_now=time.mktime (Time.strptime ('2017-09-12 11:00:00','%y-%m-%d%h:%m:%s')) Dif_time=time_now-True_timestruct_time=time.gmtime (dif_time)Print('%d months%d%d days%d minutes%d seconds'% (struct_time.tm_year-1970,struct_time.tm_mon-1, Struct_time.tm_mday-1, Struct_time.tm_hour, struct_time.tm_min,struct_time.tm_sec))

Random module
>>>ImportRandom#Random Decimals>>> Random.random ()#decimals greater than 0 and less than 10.7664338663654585>>> Random.uniform (1,3)#decimals greater than 1 and less than 31.6270147180533838#random integers>>> Random.randint (1,5)#integer greater than or equal to 1 and less than or equal to 5>>> Random.randrange (1,10,2)#odd number greater than or equal to 1 and less than 10#randomly selects a return>>> Random.choice ([1,' at', [4,5]])##1或者23或者 [4,5]#Randomly select multiple returns, the number returned is the second parameter of the function>>> Random.sample ([1,' at', [4,5]],2]##列表元素任意2个组合[4, 5],' at']#Shuffle List Order>>> item=[1,3,5,7,9]>>> Random.shuffle (item)#Shuffle Order>>>item[5, 1, 3, 7, 9]>>>random.shuffle (item)>>>item[5, 9, 7, 1, 3]

Exercise: Generate Random verification codes

Import Random def V_code ():     "'     for  in range (5):        num=random.randint (0,9)        Alf=CHR (Random.randint (65,90))        Add=random.choice ([num,alf])        code="". Join ([Code,str (add)])     return  codePrint(V_code ())
OS Module

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

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work os.chdir ("dirname") To change the current script working directory, equivalent to the shell under Cdos.curdir return to the current directory: ('.') Os.pardir Gets the parent directory string name of the current directory: ('..') Os.makedirs ('dirname1/dirname2') to generate a multi-level recursive directory Os.removedirs ('dirname1'If the directory is empty, it is deleted and recursively to the previous level of the directory, if it is also empty, then delete, and so on Os.mkdir ('dirname') to generate a single-level directory, equivalent to the shell mkdir Dirnameos.rmdir ('dirname'Delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir Dirnameos.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 ("oldname","newname") Rename File/Catalog Os.stat ('Path/filename') Get File/directory information OS.SEP output operating system-specific path delimiter, win under"\\", under Linux for"/"os.linesep Output The line terminator used by the current platform, win under"\t\n", under Linux for"\ n"os.pathsep output is used to split the file path of the string win under;, Linux is: The Os.name output string indicates the current use of the platform. Win-'NT'; Linux->'POSIX'Os.system ("Bash Command") Run the shell command to display the Os.popen directly ("Bash command). Read () Run shell commands to get execution resultsOs.environ Get System environment variable Os.pathos.path.abspath (PATH) returns path normalized absolute path Os.path.split (path) splits path into directory and file name two tuples returned Os.path.dirname (path) returns the directory of path. In fact, the first element of Os.path.split (path) os.path.basename 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, or if path does not exist, returns Falseos.path.isabs if path is an absolute path, Returns Trueos.path.isfile (path) If path is an existing file and returns True. Otherwise, return Falseos.path.isdir (path) True if path is a directory that exists.  Otherwise return Falseos.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 size of the file or directory to which path was last modified Os.path.getsize (path) returned path
OS module Methods Daquan

Note: Os.stat(' path/filename ') gets The structure description of the file/directory information

STAT structure: St_mode:inode Protected Mode st_ino:inode node number. The device that the St_dev:inode resides on. St_nlink:inode number of links. St_uid: The owner's user ID. St_gid: The group ID of the owner. St_size: The size of the normal file in bytes, including data waiting for certain special files. St_atime: Time of last visit. St_mtime: The time of the last modification. St_ctime: "ctime"reported by the operating system. On some systems, such as UNIX, is the time of the most recent metadata change, and on other systems (such as Windows) is the time of creation (see the documentation for the platform for more information).

SYS module

SYS module is an interface that interacts with the Python interpreter

sys.argv           command line argument list, the first element is the program itself path Sys.exit (n)        exits the program, exit normally exits (0), error exits Sys.exit (1) sys.version        Gets the version information of the Python interpreter 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
Import SYS Try :    sys.exit (1)except  systemexit as E:    print(e)
exception handling and status
Import= 1 while Count <10:    Print(count)    if Count = = 8:        sys.exit (    )+ = 1print('ending') Results: 12345678

JSON serialization Module

What is serialization-the process of converting an original dictionary, list, and so on into a string is called serialization .

For example, one of the data we calculate in Python code needs to be used for another program, so how do we give it? Now we can think of a method that exists in the file, and then another Python program is read from the file. But we all know that there is no dictionary concept for a file, so we can only convert the data into a dictionary and put it in a file. You must ask, it is very simple to convert a dictionary into a string, that is, str (DIC) can do it, why do we have to learn the serialization module? Yes, the process of serialization is the process of turning from DIC to STR (DIC). Now you can convert a dictionary called dic into a string by using Str (DIC), but how do you convert a string into a dictionary? You must have thought of it. Eval (), if we pass a dictionary str_dic of a string type to eval, we get a dictionary type that is returned. The eval () function is very powerful, but what does eval do? E official demo is interpreted as: the string str as a valid expression to evaluate and return the results of the calculation. but! Powerful functions are at the cost. Security is one of its biggest drawbacks. Imagine that if we read from a file is not a data structure, but a " Delete the file " similar to the destructive statement, then the consequences are not set to imagine. The use of eval is a risk. Therefore, we do not recommend using the Eval method for deserialization (converting STR to a data structure in Python)

Purpose of serialization

1. Persist the custom object in some form of storage; 2. Transfer objects from one place to another. 3, make the program more maintenance.

Json

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

Loads and dumps

The Python module time,

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.