python module time, datetime, random, os, sys

A: built-in modules

1.

time和datetime(http://www.jb51.net/article/49326.htm)

 

In Python, there are usually several ways to represent this time: 1) the time stamp 2) 3 formatted time string) tuple (struct_time) total of nine elements. Due to the time Python module to achieve the main C library calls, so each platform may vary.


UTC (Coordinated Universal Time, UTC) that is Greenwich astronomical time, the world standard time. In China is UTC + 8. DST (Daylight Saving Time) i.e. daylight saving time.

 

Timestamp (timestamp) way: Generally speaking, the timestamp indicates that from January 1970 00:00:00 1st offset press in seconds. We run "type (time.time ())", returns a float. Returns the timestamp of the way of the main function of time (), clock () and so on.

 

Tuple (struct_time) mode: struct_time tuple total of nine elements, the main function returns struct_time gmtime (), localtime (), strptime (). Here are several elements in such a manner tuple:

Coding _ * _ #: _ * _. 8 UTF- 
Import Time 


# Print (time.clock ()) # returns processor time, begin 3.3 obsolete, changed time.process_time () operation time measurement processor, not including the sleep time unstable measured out on mac 
# print (time.altzone) # returns utc time difference with time, in seconds \ 
# Print (that time.asctime ()) return time format # "Fri Aug 19 11:14:16 2016 ", 
# Print (time.localtime ()) # returns the local time of the struct time object format 
# print (time.gmtime (time.time () - 800000)) # returns utc time struc time object format 

# print (time .asctime (time.localtime ())) # returns the time format "Fri Aug 19 11:14:16 2016", 
#Print (time.ctime ()) # returns Fri Aug 19 12:38:29 2016 format, ditto 



# date stamp string to turn 
# string_2_struct = time.strptime ( "2016/05/22" , "% Y /% m /% d") # date time string converted into an object format struct 
# Print (string_2_struct) 
# # 
# timestamp into a string format 
# struct_2_stamp = Time.mktime (string_2_struct) # struct the object into a time stamp
Print # (struct_2_stamp)



# Print (time.gmtime (time.time () - 86640)) # struct_time converted into utc timestamp format 
# print (time.strftime ( "% Y- % m-% d% H:% M:% S" , time.gmtime ())) # utc struct_time will be transferred to the specified format string format 

# add or subtract 
Import datetime 

# Print (datetime.datetime.now ()) returns # 2016-08-1912: 47: 03.941925 
# print (datetime.date.fromtimestamp (time.time ()) ) # timestamp is directly converted into date format 2016-08-19 
# Print (datetime.datetime.now ()) 
# Print (datetime.datetime.now () + datetime.timedelta (3)) # current time day +3 
# print (datetime.datetime.now () + datetime.timedelta (-3)) # current time to 3 days 
# print (datetime.datetime.now () + datetime .timedelta (hours = 3)) # current time +3 hours 
# print (datetime.datetime.now () + datetime.timedelta (minutes = 30)) # current time + 30 minutes 


#
Datetime.datetime.now c_time = # () 
# Print (c_time.replace (=. 3 minute, hour = 2)) # Time Shift

  Reference format

% a local (the locale) days of the week simplified     
% A full week of local name     
% b local simplified month name     
% B full month name local     
% c corresponding local date and time representation     
% d day of the month (01 - 31)     
% H the first few hours (24-hour format, 00--23) day in     
% I first of several hours (12-hour clock, 01--12)     
day of the year,% j (001 - 366)     
% m month (01 - 12 is)     
% M minutes (00--59)     
corresponding character% p am or pm a local     
% S seconds (01--61) two     
weeks in a year% U. (00--53 Sunday is the beginning of a week.) All days prior to the first Sunday in Week 0. San     
% w first few days of the week (0 - 6,0 Sunday) Third     
% W% U and basically the same, except that% W with a week beginning Monday.    
% x corresponding local date     
% X corresponding local time     
Year% y removed century (00 - 99)     
% full year the Y-     
name% Z time zone (if there is no null character)    
%% '%' character

  2.random module

# / usr / bin / the env Python! 
# _ * _ encoding: UTF-_ * _. 8 
Import Random 
Print (random.random ()) 0.6445010863311293 #   
# random.random () for generating a random point values 0 to 1: 0 <= n-<1.0 
Print (the random.randint (l, 7)). 4 # 
# the random.randint () function prototype: random.randint (a, b), for generating an integer within a specified range. 
# Wherein A is a lower limit of the parameter, the parameter b is the upper limit, the generated random number n-: a <= n-<= b 
Print (random.randrange (1,10)). 5 # 
Function Prototype # random.randrange is: random.randrange ([Start], STOP [, STEP]), 
#, acquires a random number from within the specified range of the specified base set increments. Such as: random.randrange (10, 100, 2), 
# obtaining equivalent results from a random number [10, 12, 14, 16, ... 96, 98] in the sequence. 
# Random.randrange (10, 100, 2 ) equivalent random.choice (range (10, 100, 2) on the results. 
Print (The random.choice ( 'liukuni')) #i 
# The random.choice from the sequence Gets a random element.
# Its function prototype is: random.choice (sequence). It represents an ordered sequence parameter type. 
# Here to explain: sequence in python is not a specific type, but generally refers to a range of types. 
# List, tuple, strings belong to the sequence. You can view the relevant sequence python manual data models in this chapter. 
# Here are some examples of the use of choice: 
Print (random.choice ( "Learning Python")) # learn 
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] 
function prototype # random.sample is: random.sample (sequence, k), obtaining random fragments specified length from a specified sequence. sample function does not modify the original sequence.

  Practical application:

! # / usr / bin / Python the env 
# encoding: UTF. 8- 
Import Random 
Import String 
# random integer: 
Print (the random.randint (0,99)) # 70 

# randomly select the even-numbered 0-100: 
Print (Random. randrange (0, 101, 2)). 4 # 

# random floating point: 
Print (random.random ()) # 0.2746445568079129 
Print (random.uniform (. 1, 10)) 9.887001463194844 # 

# random characters: 
Print (The random.choice ( ' #% ^ & * ABCDEFG F ')) #f 

# plurality of characters in a certain number of characters selected: 
Print (random.sample (' ABCDEFGHIJ ',. 3)) # [' F ',' H ',' D '] 

# randomly selected strings: 
Print (The random.choice ([ 'Apple', 'PEAR', 'Peach', 'Orange', 'Lemon'])) #Apple 
# shuffling # 
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]

  Generating a random codes:

import random
checkcode = ''
for i in range(4):
    current = random.randrange(0,4)
    if current != i:
        temp = chr(random.randint(65,90))
    else:
        temp = random.randint(0,9)
    checkcode += str(temp)
print (checkcode)

  3.os module

It provides an interface to the operating system calls

The os.getcwd () Gets the current working directory, i.e., the current working directory path python script 
os.chdir ( "dirname") a script to change the current working directory; corresponding to the CD the shell 
os.curdir Returns the current directory: ( '.') 
OS .pardir Get parent directory of the current directory name string :( '..') 
os.makdirs ( 'dirname1 / dirname2') may generate a multilayer recursive directory 
os.removedirs ( 'dirname1') if the directory is empty, delete, and recursively to the parent directory, should be empty, delete, and so on 
os.mkdir ( 'dirname') to generate a single level directory; is equivalent to the shell dirname mkdir 
os.rmdir ( 'dirname') remove empty single-stage directory, if the directory is not empty can not be deleted, an error; the equivalent of a shell dirname rmdir 
os.listdir ( 'dirname') lists all the files and subdirectories in the specified directory, including hidden files, and print as a list 
os.remove () delete a file 
os.rename ( "oldname", "newname ") rename the file / directory 
os.stat ( 'path / filename') get the file / directory information 
os.sep output operation system-specific path separator, win under the "\\", to "/" under Linux 
os.linesep output line terminator used in the current platform, the win is "\ t \ n", as "\ n" under Linux 
string os.pathsep for dividing the output file path
os.name output string indicating the current use internet. win -> 'NT'; Linux -> 'the POSIX' 
os.system ( "bash the Command") to run shell commands, direct display 
os.environ acquisition system environment variables 
os.path.abspath (path) Returns the path normalized absolute path 
os .path.split (path) to the directory path and file name into tuple returned 
os.path.dirname (path) returns the path of the directory. In fact, os.path.split (path) of the first element 
os.path.basename (path) Returns the last path of the file name. How path to / \ or end, it will return a null value. I.e. The os.path.split (path) of the second element 
os.path.exists (path) path, if present, returns True; if the path does not exist, returns False 
os.path.isabs (path) if the path is an absolute path, returns True 
os.path.isfile (path) if the path is a file exists, returns True. Otherwise it returns False 
os.path.isdir (path) if the path is a directory exists, then return True. Otherwise it returns False 
os.path.join (path1 [, path2 [, ...]]) will return after a combination of multiple paths parameters before the first absolute path will be ignored 
os.path.getatime (path) return path the last access time is pointing to a file or directory
os.path.getmtime (path) Returns the file or directory path points to the last modification time

  4.sys module

sys.argv command line parameters List, the first element of the program itself is the path 
sys.exit (n) to exit the program, when the normal exit Exit (0) 
sys.version Version Get Python interpreter 
sys.maxint largest Int value 
sys .path return path search module, using initialization value of environment variable PYTHONPATH 
sys.platform returns the operating system platform name 
sys.stdout.write ( 'Please:') 
Val = sys.stdin.readline () [: -. 1]

  

 

Guess you like

Origin www.cnblogs.com/desire-desire/p/11128488.html