Basic customized type
C.__init__(self[, arg1, ...]) constructor (with some optional parameters)
C.__new__(self[, arg1, ...]) constructor (with some optional parameters); usually used to set subclasses of immutable data types.
C.__del__(self) Deconstructor
C.__str__(self) Printable character output; built-in str() and print statements
C.__repr__(self) Runtime string output; built-in repr () and '' operators
C.__unicode__(self)b Unicode string output; built-in unicode()
C.__call__(self, *args) represents a callable instance
C.__nonzero__(self) Define False value for object; built-in bool() (since version 2.2)
C.__len__(self) "length" (can be used for classes); built-in len()
Special method Description
Object (value) Compare c
C.__cmp__(self, obj) object comparison; built-in cmp()
C.__lt__(self, obj) and less than/less than or equal to; corresponding to
C.__gt__( self, obj) and greater than/greater than or equal to; corresponding to > and >= operators
C.__eq__(self, obj) and equal to/not equal to; corresponding to ==,!= and
attributesC .__getattr__(self, attr) Get the attribute; built-in getattr(); only called when the attribute is not foundC.__setattr__(self, attr, val) Set the attributeC.__delattr__(self, attr) Delete the attributeC.__getattribute__(self, attr) gets attributes; built-in getattr(); always called C.__get__(self, attr) (descriptor) gets attributes C.__set__(self, attr, val) (Descriptor) Set attribute C.__delete__(self, attr) (Descriptor) Delete attribute Custom class/simulated type Numeric type: Binary operator C.__*add__(self, obj) Add ;+ operatorC.__*sub__(self, obj) minus;-operatorC.__*mul__(self, obj) multiplication;* operatorC.__*div__(self, obj) Division;/operatorC.__*truediv__(self, obj) True division;/operatorC.__*floordiv__(self, obj) Floor division;//operatorC.__*mod__( self, obj) modulo/remainder; % operatorC.__*divmod__(self, obj) division and modulo; built-in divmod()C.__*pow__(self, obj[, mod] ) exponentiation; built-in pow(); ** operator C.__*lshift__(self, obj) left shift; Special method descriptioncustom class/simulation typenumeric type : Binary operator C.__*rshift__(self, obj) right shift; >> operator C.__*and__(self, obj) bitwise AND; & operator C.__*or__( self, obj) bitwise OR; | operator C.__*xor__(self, obj) bitwise AND or; ^ operatorNumeric type: unary operatorC.__neg__(self) unary negative
C.__pos__(self) unary positive C.__abs__(self) absolute value; built-in abs()C.__invert__(self) bitwise negation; ~ operator Numeric type: numerical conversion C.__complex__(self, com) is converted to complex (plural); built-in complex()C.__int__(self) is converted to int; built-in int()C.__long__(self) is converted to long; built-in Built long()C.__float__(self) converted to float; built-in float()Numeric type: basic representation (String)C.__oct__(self) octal representation; built-in oct() C.__hex__(self) Hexadecimal representation; built-in hex()Numeric type: numerical compressionC.__coerce__(self, num) compressed into the same numerical type; built-in coerce()C. __index__(self)g When necessary, compress the optional numeric type to an integer type (for example: for slicingindex, etc.sequence typeC.__len__(self) The number of items in the sequenceC .__getitem__(self, ind) Get a single sequence elementC.__setitem__(self, ind,val) Set a single sequence elementC.__delitem__(self, ind) Delete a single sequence elementSpecial method descriptionSequence type C.__getslice__(self, ind1,ind2) Get the sequence fragmentC.__setslice__(self, i1, i2,val) Set the sequence fragmentC.__delslice__(self, ind1,ind2) Delete the sequence fragmentC .__contains__(self, val) f test sequence members; built-in in keyword C.__*add__(self,obj) concatenation; + operator C.__*mul__(self,obj) repetition;* OperatorC.__iter__(self) creates an iterative class; built-in iter()mapping typeC.__len__(self) The number of items in the mappingC.__hash__(self) hash (hash) Function valueC.__getitem__(self,key) Get the value of the given key (key)C.__setitem__(self,key,val) Set the value of the given key (key)C.__delitem__(self, key) Delete the value of the given key (key)C.__missing__(self,key) If the given key does not exist in the dictionary, provide a default valueRemember a few commonly used python functions so as not to forgetget File extension function: Returns the extension and the file name path before the extension. os.path.splitext('xinjingbao1s.jpg')('xinjingbao1s', '.jpg')os and os.path modules os.listdir(dirname): List the directories and directories under dirname File os.getcwd(): Get the current working directory os.curdir: Return the previous directory ('.') os.chdir(dirname): Change the working directory to dirname os.path.isdir( name): Determines whether name is a directory. If name is not a directory, it returns falseos.path.isfile(name): Determines whether name is a file. If name does not exist, it returns false
os.path.exists(name): Determine whether the file or directory name exists
os.path.getsize(name): Get the file size, if name is a directory, return 0L
os.path.abspath(name): Get Absolute path
os.path.normpath(path): Normalize path string form
os.path.split(name): Split the file name and directory (in fact, if you use the directory entirely, it will also split the last The directory is separated as the file name, and it does not determine whether the file or directory exists)
os.path.splitext(): separates the file name and extension
os.path.join(path,name): joins the directory with File name or directory
os.path.basename(path): Returns the file name
os.path.dirname(path): Returns the 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 multi-level directories: os.makedirs(r"c:pythontest")
7. Create a single directory: os.mkdir("test")
8. Delete multiple directories: os .removedirs(r"c:python") #Delete all empty directories under the last directory of the given path.
9. Delete a single directory: os.rmdir("test")
10. Get file attributes: os.stat(file)
11. Modify file permissions and timestamp: os.chmod(file)
12 .Execute operating system commands: os.system("dir")
13. Start a new process: os.exec(), os.execvp()
14. Execute a program in the background: osspawnv()
15. Terminate Current process: os.exit(), os._exit()
16. Split file name: os.path.split(r"c:pythonhello.py") --> ("c:\python", "hello .py")
17. Separate extension: os.path.splitext(r"c:pythonhello.py") --> ("c:\python\hello", ".py")
18. Get Path name: os.path.dirname(r"c:pythonhello.py") --> "c:\python"
19. Get the file name: os.path.basename(r"r:pythonhello.py") --> "hello.py"
20. Determine whether the file exists: os.path.exists(r"c:pythonhello.py") --> True
21. Determine whether it is an absolute path: os.path. isabs(r".python") --> False
22. Determine whether it is a directory: os.path.isdir(r"c:python") --> True
23. Determine whether it is a file: os.path .isfile(r"c:pythonhello.py") --> True
24. Determine whether it is a link file: os.path.islink(r"c:pythonhello.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 a temporary file: tempfile.TemporaryFile()
[4.StringIO] #cStringIO is a fast implementation module of the StringIO module
1. Create a memory file and write initial data: f = StringIO.StringIO("Hello world !")
2. Read data into the memory file: print f.read() #or print f.getvalue() --> Hello world!
3. Write data into the memory file: f.write("Good day!")
4. Close the memory file: f.close()
View source code printing 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)
7 '2008-11-25 23:51:20'
Output the specified struct_time (default is the current time) according to the specified format string
Time and date formatting symbols in python:
%y two-digit year representation (00-99)
%Y Four-digit year representation (000-9999)
%m month (01-12)
%d day of the month (0-31)
%H 24-hour hour (0-23)
%I Hours in 12-hour format (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 complete month name
%c Local corresponding date representation and time representation
%j Day in the year (001-366)
%p Local A.M. or P.M. The equivalent of
%U The number of weeks in a year (00-53) Sunday is the beginning of the week
%w The day of the week (0-6), Sunday is the beginning of the week
%W The number of weeks in a year (00-53) Monday is the beginning of the week
%x The corresponding local date representation
%X The corresponding local time representation
%Z The name of the current time zone
%% The % number itself
9.strptime( …)
strptime(string, format) -> struct_time
Convert the time string into an array of time according to the specified formatter
For example:
2009-03-20 11:45:39 Corresponding format The format string is: %Y-%m-%d %H:%M:%S
Sat Mar 28 22:24:24 2009 The corresponding format string is: %a %b %d %H:% M:%S %Y
10.time(…)
time() -> floating point number
Returns the timestamp of the current time
3. Doubts
1. Daylight saving time
In struct_time, daylight saving time It seems useless, 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 represent daylight saving time and standard time respectively. The conversion between them into timestamps should be related to 3600, but the conversion The final output is 646585714.0
4. Mini application
1.python gets the current time
time.time() gets the current timestamp
time.localtime() the struct_time form of the current time
time.ctime() current The string form of time
2. python format string
Format it into the form of 2009-03-20 11:45:39
time.strftime("%Y-%m-%d %H:%M: %S", time.localtime()) is formatted into Sat Mar 28 22:24:24 2009 format
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"))
Detailed explanation of python time datetime module
Time module:
--------------------- --
time() #Return the number of seconds elapsed since the Linux new century in floating point form. 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'
time.ctime([sec ]) #Convert seconds to date format. If there are no parameters, the current time will be displayed.
>>> import time
>>> time.ctime()
>>> 'Wed Jun 14 15:02:50 2006'
>>> time.ctime(1138068452427683)
'Sat Dec 14 04:51:44 1901'
>>> time.ctime(os.path.getmtime('E:\untitleds.bmp'))
'Fri Sep 19 16:35:37 2008'
>>> time.gmtime(os.path.getmtime('E:\untitleds.bmp'))
time.struct_time(tm_year=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 date format (seconds to date)
>>> time.strftime('%Y-%m-%d % X',time.localtime(os.path.getmtime('E:\untitleds.bmp')))
'2008-09-19 16:35:37'
#Timing 3 seconds.
>>> time.sleep(3)
TIME module reference:
---------------------------- --
#Get the modification time of a file
>>> os.path.getmtime('E:\untitleds.bmp')
1221813337.7626641
Variable
timezone The difference between universal coordinated time and local standard time , in seconds.
altzone The difference between Universal Coordinated Time and local daylight saving time
daylight flag, whether local time reflects daylight saving time.
tzname (standard time zone name, daylight saving time zone name)
function
time() returns the number of seconds since the epoch as a floating point number.
clock() returns the time when the CPU started this process as a floating point number, (or the time since the last time this function was called)
sleep() delays for a number of seconds expressed as a floating point number.
gmtime() Convert time expressed in seconds to general coordinated time series
localtime() Convert seconds to local time series
asctime() Convert time series to text description
ctime() Convert seconds to time Convert to text description
mktime() Convert local time series to seconds
strftime() Convert time series to text description in the specified format
strptime() Parse the time series from the text description in the specified format
tzset() changes the local time zone value
DateTime module
---------------------------
datetime Convert date to seconds
------------------------------------------------
>>> import datetime,time
> >> time.mktime(datetime.datetime(2009,1,1).timetuple())
1230739200.0
>>> cc=[2000,11,3,12,43,33] #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
----------------
Demonstration of calculating the number of days difference between two dates Calculate
>>> import datetime
>>> d1 = datetime.datetime(2005, 2, 16)
>>> d2 = datetime.datetime(2004, 12, 31)
>>> (d1 - d2).days
47
Demonstrates an example of calculating running time, displayed in seconds
import datetime
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now( )
print (endtime - starttime).seconds
demonstrates calculating the time 10 hours backward from the current time.
>>> d1 = datetime.datetime.now()
>>> d3 = d1 + datetime.timedelta(hours=10)
>>> d3.ctime()
The commonly used classes are : Two datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and properties to view specific values