Basic custom C _ init _ (self [, arg1,]) constructor (with some optional parameters) C _ new _ (self [, arg1,]) constructor (with some optional parameters); basic customization type
C. _ init _ (self [, arg1,...]) constructor (with some optional parameters)
C. _ new _ (self [, arg1,...]) constructor (with some optional parameters); it is usually used to set a subclass of the unchanged data type.
C. _ del _ (self) deconstruct
C. _ str _ (self) printable character output; built-in str () and print statements
C. _ repr _ (self) string output during runtime; built-in repr () and ''operators
C. _ unicode _ (self) B Unicode string output; built-in unicode ()
C. _ call _ (self, * args) indicates the callable instance.
C. _ nonzero _ (self) defines the False value for the object; built-in bool () (starting from version 2.2)
C. _ len _ (self) "length" (can be used for classes); built-in len ()
Special method description
Object (value) comparison c
C. _ cmp _ (self, obj) object comparison; built-in cmp ()
C. _ lt _ (self, obj) and less than/or equal; <及<=操作符< p>
C. _ gt _ (self, obj) and greater than/or equal to; corresponding to> and> = operators
C. _ eq _ (self, obj) and equals/not equal to; corresponding = ,! = And <> operators
Attribute
C. _ getattr _ (self, attr) get attributes; built-in getattr (); called only when the attribute is not found
C. _ setattr _ (self, attr, val) set attributes
C. _ delattr _ (self, attr) delete attributes
C. _ getattribute _ (self, attr) get attributes; built-in getattr (); always called
C. _ get _ (self, attr) (descriptor) get attributes
C. _ set _ (self, attr, val) (descriptor) set attributes
C. _ delete _ (self, attr) (descriptor) delete attributes
Custom class/simulation type
Value type: binary operator
C. _ * add _ (self, obj) plus; + operator
C. _ * sub _ (self, obj) subtraction;-operator
C. _ * mul _ (self, obj) multiplication; * operator
C. _ * p _ (self, obj) Division;/operator
C. _ * truep _ (self, obj) True division;/operator
C. _ * floorp _ (self, obj) Floor Division; // operator
C. _ * mod _ (self, obj) modulo/remainder; % operator
C. _ * pmod _ (self, obj) division and modulo; built-in pmod ()
C. _ * pow _ (self, obj [, mod]) multiplication power; built-in pow (); ** operator
C. _ * lshift _ (self, obj) left shift; < <操作符< p>
Special method description
Custom class/simulation type
Value type: binary operator
C. _ * rshift _ (self, obj) shifts right;> operator
C. _ * and _ (self, obj) bitwise and; & Operator
C. _ * or _ (self, obj) bitwise or; | operator
C. _ * xor _ (self, obj) bitwise and or; ^ operator
Value type: unary operator
C. _ neg _ (self) negative of one dollar
C. _ pos _ (self) mona1 positive
C. _ abs _ (self) absolute value; built-in abs ()
C. _ invert _ (self) reverse by bit ;~ Operator
Value type: Numerical conversion
C. _ complex _ (self, com) to complex (plural); built-in complex ()
C. _ int _ (self) to int; built-in int ()
C. _ long _ (self) to long; built-in long ()
C. _ float _ (self) to float; built-in float ()
Value type: basic notation (String)
C. _ oct _ (self) octal representation; built-in oct ()
C. _ hex _ (self) hexadecimal representation; built-in hex ()
Numeric Type: Numerical compression
C. _ coerce _ (self, num) compressed to the same numeric type; built-in coerce ()
C. _ index _ (self) g. when necessary, compress the optional numeric type into an integer (for example, used for slicing ).
Index, etc.
Sequence Type
Number of items in the C. _ len _ (self) sequence
C. _ getitem _ (self, ind) to obtain a single sequence element
C. _ setitem _ (self, ind, val) set a single sequence element
C. _ delitem _ (self, ind) delete a single sequence element
Special method description
Sequence Type
C. _ getslice _ (self, ind1, ind2) to obtain the sequence segment
C. _ setslice _ (self, i1, i2, val)
C. _ delslice _ (self, ind1, ind2) delete a sequence segment
C. _ contains _ (self, val) f test sequence member; built-in in keyword
C. _ * add _ (self, obj) concatenate; + operator
C. _ * mul _ (self, obj) repetition; * operator
C. _ iter _ (self) create iteration class; built-in iter ()
Ing type
C. _ len _ (self) number of items in ING
C. _ hash _ (self) hash function value
C. _ getitem _ (self, key) get the value of the given key.
C. _ setitem _ (self, key, val) sets the value of the given key.
C. _ delitem _ (self, key) delete the value of the given key
C. _ missing _ (self, key) if the given key does not exist in the dictionary, a default value is provided.
Remember several common python functions to avoid forgetting
Get the file extension function: return the file name path before the extension and extension.
OS .path.splitext('xinjingbao1s.jpg ')
('Xinjingbao1s ', '.jpg ')
OS and OS. path modules
OS. listdir (dirname): list directories and files under dirname
OS. getcwd (): get the current working directory
OS. curdir: returned but the former Directory ('.')
OS. chdir (dirname): change the working directory to dirname
OS. path. isdir (name): determines whether the name is a directory. if the name is not a directory, false is returned.
OS. path. isfile (name): determines whether the name is a file. if the name does not exist, false is returned.
OS. path. exists (name): determines whether a file or directory name exists.
OS. path. getsize (name): get the file size. if the name is a directory, return 0L
OS. path. abspath (name): obtain the absolute path.
OS. path. normpath (path): Standard path string format
OS. path. split (name): split the file name and Directory (in fact, if you fully use the directory, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)
OS. path. splitext (): separates file names and extensions
OS. path. join (path, name): connection directory and file name or directory
OS. path. basename (path): returns the file name.
OS. path. dirname (path): return file path
1. rename: OS. rename (old, new)
2. delete: OS. remove (file)
3. list the files in the directory: OS. listdir (path)
4. get the current working directory: OS. getcwd ()
5. change the working directory: OS. chdir (newdir)
6. create a multilevel Directory: OS. makedirs (r "c: \ python \ test ")
7. create a single directory: OS. mkdir ("test ")
8. delete multiple directories: OS. removedirs (r "c: \ python") # Delete all empty directories in the last Directory of the given path.
9. delete a single directory: OS. rmdir ("test ")
10. Get file attributes: OS. stat (file)
11. modify the file permission and timestamp: OS. chmod (file)
12. execute the operating system command: OS. system ("dir ")
13. start a new process: OS .exe c (), OS .exe cvp ()
14. execute the program in the background: osspawnv ()
15. terminate the current process: OS. exit (), OS. _ exit ()
16. separated File name: OS. path. split (r "c: \ python \ hello. py") --> ("c: \ python", "hello. py ")
17. separation extension: OS. path. splitext (r "c: \ python \ hello. py ") --> (" c: \ python \ hello ",". py ")
18. obtain the path name: OS. path. dirname (r "c: \ python \ hello. py") --> "c: \ python"
19. get the file name: OS. path. basename (r "r: \ python \ hello. py") --> "hello. py"
20. determine whether the file exists: OS. path. exists (r "c: \ python \ hello. py") --> True
21. determine whether the path is absolute: OS. path. isabs (r ". \ python \") --> False
22. check whether the directory is OS. path. isdir (r "c: \ python") --> True
23. determine whether the file is: OS. path. isfile (r "c: \ python \ hello. py") --> True
24. determine whether the file is a linked File: OS. path. islink (r "c: \ python \ hello. py") --> False
25. Get file size: OS. path. getsize (filename)
26. *******: OS. ismount ("c: \") --> True
27. search all files in the directory: OS. path. walk ()
[2. shutil]
1. copy a single file: shultil. copy (oldfile, newfle)
2. copy the entire directory tree: shultil. copytree (r ". \ setup", r ". \ backup ")
3. delete the entire directory tree: shultil. rmtree (r ". \ backup ")
[3. tempfile]
1. create a unique temporary file: tempfile. mktemp () --> filename
2. open the temporary file: tempfile. TemporaryFile ()
[4. StringIO] # cStringIO is a fast implementation module of the StringIO module.
1. create a memory file and write the initial data: f = StringIO. StringIO ("Hello world! ")
2. read memory file data: print f. read () # or print f. getvalue () --> Hello world!
3. write data to memory files: f. write ("Good day! ")
4. close the memory File: f. close ()
View source code print help 1 from time import *
2
3 def secs2str (secs ):
4 return strftime ("% Y-% m-% d % H: % M: % S", localtime (secs) 5
5
6 >>> secs2str (1227628280.0)
2008-11-25 23:51:20'
Returns the specified struct_time (current time by default) according to the specified formatted string.
Time and date formatting symbols in python:
% Y two-digit year (00-99)
% Y indicates the four-digit year (000-9999)
% M month (01-12)
One day in % d Month (0-31)
% H Hour in 24-hour format (0-23)
% I 12-hour (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 date and time
% J one day in the year (001-366)
% P local equivalent of A. M. or P. M.
% U number of weeks in a year (00-53) Sunday is the start of the week
% W week (0-6), Sunday is the beginning of the week
% W number of weeks in a year (00-53) Monday is the start of the week
% X local date representation
% X local time representation
% Z current time zone name
% Itself
9. strptime (...)
Strptime (string, format)-> struct_time
Converts a time string to a time string in the array format based on the specified formatting character.
For example:
The format string for 11:45:39 is: % Y-% m-% d % H: % M: % S
Sat Mar 28 22:24:24 2009 formatted string: % a % B % d % H: % M: % S % Y
10. time (...)
Time ()-> floating point number
Returns the timestamp of the current time.
III. doubts
1. renewal
In struct_time, it seems useless to parse, for example
A = (2009, 6, 28, 23, 8, 34, 5, 87, 1)
B = (2009, 6, 28, 23, 8, 34, 5, 87, 0)
A and B indicate the time stamp and the standard time respectively. the conversion between them is related to the timestamp 3600, but the output is 646585714.0 after the conversion.
4. small applications
1. obtain the current time using python
Time. time () get the current timestamp
Time. localtime () struct_time form of the current time
Time. ctime () string format of the current time
2. format strings in python
Formatted as 11:45:39
Time. strftime ("% Y-% m-% d % H: % M: % S", time. localtime () is formatted as Sat Mar 28 22:24:24 2009
Time. strftime ("% a % B % d % H: % M: % S % Y", time. localtime () 3. convert the format string to a timestamp
A = "Sat Mar 28 22:24:24 2009"
B = time. mktime (time. strptime (a, "% a % B % d % H: % M: % S % Y "))
Python time datetime module details
Time module:
--------------------------
Time () # returns the number of seconds since the Linux New Century in floating point format. In linux, 00:00:00 UTC,
January 1, 1970 is the beginning of the New ** 49.
>>> Time. time ()
1150269086.6630149
>>> Time. ctime (1150269086.6630149)
>>> 'Wed Jun 14 15:11:26 123'
Time. ctime ([sec]) # converts the number of seconds to the date format. If no parameter is included, the current time is displayed.
>>> Import time
>>> Time. ctime ()
>>> 'Wed Jun 14 15:02:50 123'
>>> Time. ctime (1138068452427683)
'Sat Dec 14 04:51:44 123'
>>> Time. ctime (OS. path. getmtime ('E: \ untitleds.bmp '))
'Fri Sep 19 16:35:37 123'
>>> Time. gmtime (OS. path. getmtime ('E: \ untitleds.bmp '))
Time. struct_time (maid = 2008, tm_mon = 9, tm_mday = 19, tm_hour = 8, tm_min = 35,
Tm_sec = 37, tm_wday = 4, tm_yday = 263, tm_isdst = 0)
Convert the modification time of a file to the date format (second to date)
>>> Time. strftime ('% Y-% m-% d % X', time. localtime (OS. path. getmtime ('E: \ untitleds.bmp ')))
'2017-09-19 16:35:37'
# Timed for 3 seconds.
>>> Time. sleep (3)
TIME module reference:
---------------------------------
# Retrieve the modification time of an object
>>> OS. path. getmtime ('E: \ untitleds.bmp ')
1221813337.7626641
Variable
The difference between the timezone Universal coordination time and the local standard time, in seconds.
Difference between the altzone universal coordination time and local compaction time
Daylight indicates whether the local time reflects the daylight saving time.
Tzname (standard time zone name, time zone name in milliseconds)
Function
Time () returns the number of seconds since the epoch.
Clock () returns the time when the CPU starts the process with a floating point number (or the time when the function is called the first time)
Sleep () delays the number of seconds represented by floating points.
Gmtime () converts the time expressed in seconds to a Universal Coordinated Time sequence.
Localtime () converts seconds to local time series
Asctime () converts a time series into a text description
Ctime () converts a second to a text description
Mktime () converts a local time sequence to a second
Strftime () converts a sequence to a text description in a specified format
Strptime () parses time series from text descriptions in a specified format
Tzset () changes the local time zone value
DateTime module
----------------------------
Datetime converts a date to a second.
-------------------------------------
>>> Import datetime, time
>>> Time. mktime (datetime. datetime (2009, 1, 1). timetuple ())
1230739200.0
>>> Cc = [, 11,] # Attributes: year, month, day, hour, minute,
Second
>>> Time. mktime (datetime. datetime (cc [0], cc [1], cc [2], cc [3], cc [4], cc [5]). timetuple ())
973226613.0
Convert seconds to date format
>>> Cc = time. localtime (OS. path. getmtime ('E: \ untitleds.bmp '))
>>> Print cc [0: 3]
(2008, 9, 19)
DateTime example
-----------------
Computing the number of days for calculating the difference between two dates
>>> Import datetime
>>> D1 = datetime. datetime (2005, 2, 16)
>>> D2 = datetime. datetime (2004, 12, 31)
>>> (D1-d2). days
47
Demo of computing run time, displayed in seconds
Import datetime
Starttime = datetime. datetime. now ()
# Long running
Endtime = datetime. datetime. now ()
Print (endtime-starttime). seconds
This example calculates the time from the current time to the next 10 hours.
>>> D1 = datetime. datetime. now ()
>>> D3 = d1 + datetime. timedelta (hours = 10)
>>> D3.ctime ()
Common classes include datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values.