Home > Backend Development > Python Tutorial > Python basic syntax encyclopedia

Python basic syntax encyclopedia

巴扎黑
Release: 2017-08-02 10:19:32
Original
9476 people have browsed it

1. Python’s support for Chinese characters

#!/usr/bin/python
#coding: UTF-8
print "Hello, world";

2. Python identifier

In python, identifiers are composed of letters, numbers, and underscores.

In python, all identifiers can include English, numbers, and underscores (_), but cannot start with numbers.

#Identifiers in Python are case-sensitive.

#Identifiers starting with an underscore have special meaning. Class attributes starting with a single underscore (_foo) represent class attributes that cannot be accessed directly. They need to be accessed through the interface provided by the class and cannot be imported using "from xxx import *";

(__foo) starting with a double underscore represents the private members of the class; (__foo__) starting and ending with a double underscore represents a special identifier for special methods in python, such as __init__() representing the constructor of the class.

3. python reserved keywords

and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

4. Python string representation

Python accepts single quotes (' ), double quotes (" ), Triple quotes (''' """) are used to represent strings. The beginning and end of the quotes must be of the same type.

Three quotation marks can be composed of multiple lines, which is a shortcut syntax for writing multi-line text. Commonly used document strings are used as comments at specific locations in the file.

word = 'word'sentence = "这是一个句子。"paragraph = """这是一个段落。
包含了多个语句"""
Copy after login

5. The main annotations in Python are

# or ''' ''' or "" """

6. Python data types:

  • ##Numbers (number

    )

    • int (signed integer type)

    • long (long integer type [can also represent octal and hexadecimal])

    • float (floating point)

    • complex (plural)

  • String (string) {

  • ##The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repeat operation:

  • !/usr/bin/python

    # -*- coding: UTF-8 -*-


    str = 'Hello World!'

    print str # Output complete characters String
    print str[0] # Output the first character in the string
    print str[2:5] # Output the third to fifth characters in the string
    print str[2:] # Output the string starting from the third character
    print str * 2 # Output the string twice
    print str + "TEST" # Output the connected string

  • }
  • List (list)
  • {

  • #!/usr/bin/python

    # -*- coding: UTF-8 -*-


    list = [ 'abcd', 786 , 2.23, 'john' , 70.2 ]
    tinylist = [123, 'john']

    print list # Output the complete list
    print list[0] # Output the first element of the list
    print list[1 :3] # Output the second to third elements
    print list[2:] # Output all elements from the third to the end of the list
    print tinylist * 2 # Output the list twice
    print list + tinylist #Print the combined list

    Output result of the above example:



    ['abcd', 786, 2.23, 'john', 70.2]
    abcd
    [786, 2.23]
    [2.23, 'john', 70.2]
    [123, 'john', 123, 'john']
    ['abcd', 786, 2.23, ' john', 70.2, 123, 'john']

  • }

  • Tuple

  • {

  • Tuples are marked with "()". Internal elements are separated by commas. But is that the tuple cannot be assigned twice, which is equivalent to a read-only list.


    #!/usr/bin/python
    # -*- coding: UTF-8 -*-

    tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
    tinytuple = (123, 'john')

    print tuple # Output the complete tuple
    print tuple[0] # Output the tuple The first element of the group
    print tuple[1:3] # Output the second to third elements
    print tuple[2:] # Output all elements starting from the third to the end of the list
    print tinytuple * 2 # Output the tuple twice
    print tuple + tinytuple # Print the combined tuple

    Output result of the above example:


    ('abcd', 786, 2.23, 'john', 70.2)
    abcd
    (786, 2.23)
    (2.23, 'john', 70.2)
    (123, ' john', 123, 'john')
    ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

    The following tuple is invalid because Tuples are not allowed to be updated. The list is allowed to be updated:


    !/usr/bin/python
    # -*- coding: UTF-8 -*-

    tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
    list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
    tuple[2] = 1000 # Tuple Illegal applications are in
    list[2] = 1000 # Legal applications are in the list

  • ##}

  • Dictionary

  • {

  • Dictionaries are identified with "{ }". A dictionary consists of an index (key) and its corresponding value.


    #!/usr/bin/python
    # -*- coding: UTF-8 -*-

    dict = {}
    dict['one'] = "This is one "
    dict[2] = "This is two"

    tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


    print dict['one'] # Output the value with key 'one'
    print dict[2] # Output the value with key 2
    print tinydict # Output the complete dictionary
    print tinydict .keys() # Output all keys
    print tinydict.values() # Output all values ​​

    The output result is:


    This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john ']

  • ##}

7. Python data type conversion

Function Description##long(x [,base] )Convert x to a long integerfloat(x)Convert x to a floating point number
int(x [ ,base])

Convert x to an integer

complex(real [,imag])

Create a complex number

str(x)

Convert object x to string

repr(x )

Convert object x to expression string

##eval(str)

Used to evaluate a valid Python expression in a string and return an object

tuple(s)

Convert sequence s into a tuple

list(s)

Convert Sequence s is converted into a list

set(s)

Convert to a variable set

dict(d)

Create a dictionary. d must be a sequence of (key, value) tuples.

frozenset(s)

Convert to immutable collection

chr(x)

Convert an integer to a character

unichr( x)

Convert an integer to Unicode characters

##ord(x)

Convert a character to its integer value

hex(x)

Convert an integer to a hexadecimal string

oct(x)

Convert an integer to an octal string

8. Python’s operators

Python’s arithmetic operators

##%Modulo- Returns the remainder of division b % a Output result 0**Power - Returns the y power of x a**b is 10 raised to the 20th power, and the output result is 100000000000000000000//Return the integer part of the quotient9/ /2 Output result 4, 9.0//2.0 Output result 4.0

Python comparison operators

+Add - Add two objectsa + b Output result 30
-Subtract - Get a negative number or one number minus another numbera - b Output result-10
*Multiply - Multiply two numbers or return a string repeated several timesa * b Output result 200
/Division - x divided by yb / a Output result 2
##OperatorDescription Example==Equal - Compare objects for equality(a == b) Return False. !=Not equal to - Compares whether two objects are not equal(a != b) Returns true.<>Not equal to - Compares whether two objects are not equal(a <> b) Returns true. This operator is similar to != . >Greater than - Returns whether x is greater than y(a > b) Returns False. <Less than - Returns whether x is less than y. All comparison operators return 1 for true and 0 for false. These are equivalent to the special variables True and False respectively. Note the capitalization of these variable names. (a < b) returns true. >=Greater than or equal to - Returns whether x is greater than or equal to y. (a >= b) Returns False. <=Less than or equal to - Returns whether x is less than or equal to y. (a <= b) returns true.

Python’s assignment operator

##OperatorDescription Example=Simple assignment operatorc = a + b assigns the operation result of a + b For c+= the additive assignment operator c += a is equivalent to c = c + a-=Subtractive assignment operatorc -= a is equivalent to c = c - a*=Multiplication assignment operatorc *= a is equivalent to c = c * a##/=##%=modulo assignment operatorc %= a Equivalent to c = c % a**=Power assignment operatorc **= a Equivalent to c = c * * aTake the integer division assignment operator
Division assignment operatorc /= a is equivalent to c = c / a
##//=
c //= a is equivalent to c = c // a

python bitwise operators

#OperatorDescriptionExample&Bitwise AND operator: Two values ​​participating in the operation. If both corresponding bits are 1, then the bit The result is 1, otherwise it is 0(a & b) The output result is 12, binary interpretation: 0000 1100##|##^Bitwise XOR operator: when two corresponding When the binary bits are different, the result is 1(a ^ b) and the output result is 49. Binary interpretation: 0011 0001~ bitwise Negation operator: Negate each binary bit of the data, that is, change 1 to 0, and change 0 to 1(~a) The output result is -61, binary interpretation: 1100 0011, in a The two's complement form of a signed binary number. Left shift operator: Each binary digit of the operand is shifted to the left by a certain number of bits, specified by the number on the right of "<<" The number of digits to move, the high bits are discarded, and the low bits are filled with 0s. Right shift operator: " >>"All binary digits of the operand on the left are shifted to the right by a certain number of digits,">>"The number on the right specifies the number of digits to move
bitwise OR Operator: As long as one of the two corresponding binary bits is 1, the result bit is 1. (a | b) The output result is 61, binary interpretation: 0011 1101
##<<
a << 2 The output result is 240, binary interpretation: 1111 0000>>
a >> 2 The output result is 15, binary Explanation: 0000 1111

python logical operators

##OperatorLogical expression FormulaDescriptionExampleandx and yBoolean "AND" - if x If False, x and y return False, otherwise it returns the calculated value of y. (a and b) returns 20. orx or yBoolean "or" - if x is True, it returns True, otherwise it returns the calculated value of y. (a or b) returns 10. notnot xBoolean "not" - If x is True, returns False. If x is False, it returns True. not(a and b) returns False

Member operators of python

##OperatorDescription Examplein Returns True if the value is found in the specified sequence, False otherwise. x is in the y sequence, returns True if x is in the y sequence. not in Returns True if the value is not found in the specified sequence, False otherwise. x is not in the y sequence, returns True if x is not in the y sequence.

Priority of python

##~ + -Bitwise flip , unary plus sign and minus sign (the last two methods are named +@ and -@)* / % //Multiplication, division, modulo Sum and division+ -Addition and subtraction>> <<Right shift, left shift operator& bit 'AND'^ |bit operator<= < > >=Comparison operator<> ; == !=Equal operator= %= /= //= -= += *= **=Assignment Operatoris is notIdentity operator##in not innot or and

Python’s mathematical functions

**Index (highest priority)
Membership operator
logical operators
FunctionReturn value (description)
abs(x)Returns the absolute value of the number Value, such as abs(-10) returns 10
ceil(x)Returns the upper integer of the number, such as math.ceil(4.1) returns 5
cmp(x, y)If x < y returns -1, if x == y returns 0, if x > y returns 1
exp(x)Returns the x power of e (ex), such as math.exp(1) returns 2.718281828459045
fabs(x) Returns the absolute value of the number, such as math.fabs(-10) returns 10.0
floor(x)Return the rounded integer of the number, such as math.floor(4.9) returns 4
log(x)For example, math.log(math.e) returns 1.0, math.log(100,10) returns 2.0
log10(x)Returns the logarithm of x with base 10 as the base, such as math.log10( 100) Return 2.0
max(x1, x2,...)Returns the maximum value of the given parameter, and the parameter can be a sequence.
min(x1, x2,...)Returns the minimum value of the given parameter, which can be a sequence.
modf(x)Returns the integer part and decimal part of x. The numerical signs of the two parts are the same as x, and the integer part is expressed in floating point type.
pow(x, y)x**y Value after operation.
round(x [,n])Returns the rounded value of the floating point number x. If the n value is given, it represents the number of digits rounded to the decimal point. .
sqrt(x)Returns the square root of the number x. The number can be negative and the return type is real number. For example, math.sqrt(4) returns 2+0j

python random function

Random numbers can be used in mathematics, games, security and other fields, and are often embedded in algorithms , to improve algorithm efficiency and improve program security.

Python contains the following commonly used random number functions:

FunctionDescription
choice (seq)Randomly select an element from the elements of the sequence, such as random.choice(range(10)), randomly select an integer from 0 to 9.
randrange ([start,] stop [,step])Get a random number from the set in the specified range, incremented by the specified base, the base is default The value is 1
random()Randomly generates the next real number, which is in the range [0,1).
seed([x])Change the seed of the random number generator. If you don't understand the principle, you don't have to set the seed specifically, Python will choose the seed for you.
shuffle(lst)Randomly sort all elements of the sequence
uniform(x, y) Randomly generate the next real number, which is in the range [x, y].

Trigonometric functions of python

##acos(x)Return the arc cosine radians value of x. asin(x)Returns the arcsine radians value of x. atan(x)Returns the arctangent radian value of x. atan2(y, x)Returns the arctangent of the given X and Y coordinate values. cos(x)Returns the cosine of x in radians. ##hypot(x, y)sin(x)tan(x)
NumberDescription




Returns the Euclidean norm sqrt(x*x + y*y) .
Returns the sine value of x radians.
Returns the tangent of x in radians.
degrees(x)Convert radians to degrees, such as degrees(math.pi/2), return 90.0
radians(x)Convert angles to radians

Python's built-in string functions

##string.center(width) Returns an original string centered and filled with spaces New string to length width##string.count(str, beg=0, end=len(string))string.decode(encoding='UTF-8', errors='strict')Check whether str is included in string. If beg and end specify the range, check whether it is included in the specified range. If it is, return the starting index value, otherwise return -1The same as the find() method, only However, if str is not in string, an exception will be reported.##string.isdecimal()Returns True if string contains only decimal digits, otherwise returns False.##string.isdigit()##string.islower()string.isnumeric()##string.istitle()Returns True if string is titled (see title()), otherwise returns Falsestring.isupper( )Returns True if string contains at least one case-sensitive character and all these (case-sensitive) characters are uppercase, otherwise it returns FalseUsing string as the separator, join all elements in seq (String representation) merged into a new string string.ljust(width) Return A new string that aligns the original string to the left and pads it with spaces to length width##string.lower()##string.maketrans(intab, outtab])maketrans( ) method is used to create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string representing the character that needs to be converted, and the second parameter is also the string representing the target of conversion. max(str) Returns the largest letter in the string min(str)Returns the smallest letter in the string ##string.partition(str)##string.swapcase()Reverse case in stringstring.title()
##MethodDescription
string.capitalize()

Put the first string uppercase characters

Returns the number of times str appears in string. If beg or end is specified, returns the number of times str appears in the specified range.

Decode string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'

string.encode(encoding='UTF-8', errors='strict')

The encoding specified by encoding Format encoding string, if an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'

string.endswith( obj, beg=0, end=len(string))

Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. End, if yes, return True, otherwise return False.

##string.expandtabs(tabsize=8)

Convert the tab symbol in the string string to spaces. The default number of spaces for the tab symbol is 8.

##string.find(str, beg=0, end=len(string))

string.index(str, beg=0, end=len(string))

string.isalnum()

Returns ## if string has at least one character and all characters are letters or numbers

#Return True, otherwise return False

string.isalpha()

If string has at least one character and all characters are letters, return True,

Otherwise, return False

If string only contains numbers, return True otherwise return False.

Returns True if string contains at least one case-sensitive character and all of these (case-sensitive) characters are lowercase, otherwise False

If the string contains only numeric characters, return True, otherwise return False

##string.isspace()

If the string contains only spaces, return True, otherwise return False.

string.join(seq)

Convert all uppercase characters in string to lowercase.

##string.lstrip()

Truncate the spaces to the left of string

str

.

str

.

A bit like find() and split( ), starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, then string_pre_str == string.

string.replace(str1, str2, num=string.count(str1))

Replace str1 in string with str2. If num is specified, the replacement will not exceed num times.

string.rfind(str, beg=0,end= len(string) )

Similar to the find() function, but starting from the right.

string .rindex(str, beg=0,end=len(string))

Similar to index(), but starts from the right.

string.rjust(width)

Returns a new string with the original string right-aligned and padded with spaces to length width

string.rpartition(str)

Similar to the partition() function, but starts searching from the right.

string.rstrip()

Remove string spaces at the end of the string.

string.split(str="", num=string.count(str))

Use str as the delimiter to slice string. If num has a specified value, only num substrings will be separated.

##string.splitlines(num=string.count( '\n'))

Separated by row, return a list containing each row as an element. If num is specified, only num rows will be sliced.

string.startswith(obj, beg=0,end=len(string))

Check whether the string starts with obj, if so, return True, otherwise returns False. If beg and end specify values, check within the specified range.

string.strip([obj])

Execute lstrip() and rstrip() on string

Returns a "titled" string, that is, all words start with uppercase letters, and the remaining letters are lowercase (see istitle())

string.translate(str, del="")

Convert string according to the table (containing 256 characters) given by str Characters,

Put the characters to be filtered out in the del parameter

string.upper()

Convert the lowercase letters in string to uppercase

string.zfill(width)

The return length is The string of width, the original string string is right-aligned, and the front is filled with 0

string.isdecimal()

The isdecimal() method checks whether a string contains only decimal characters. This method only exists for unicode objects.

Python's List function

##Serial numberFunction1cmp(list1, list2)2len(list)3max(list)4min(list)5list(seq)

Python contains the following methods:

Compare the elements of two lists
Number of list elements
Returns the maximum value of list elements
Returns the minimum value of the list element
Convert tuple to list
Serial numberMethod
1 list.append(obj)
Add a new object at the end of the list
2list.count(obj)
Count the number of elements in the list The number of occurrences in
3list.extend(seq)
Append multiple values ​​from another sequence at the end of the list at once (use a new list Expand the original list)
4list.index(obj)
Find the index position of the first matching item of a value from the list
5list.insert(index, obj)
Insert object into the list
6list.pop(obj=list[-1])
Remove an element in the list (the last element by default) and return the value of the element
7 list.remove(obj)
Remove the first occurrence of a value in the list
8list.reverse ()
Elements in the reverse list
9list.sort([func])
Sort the original list

Python tuples’ built-in functions

The Python tuple contains the following built-in functions

Serial numberMethod and description
1cmp(tuple1, tuple2)
Compare two tuple elements.
2len(tuple)
Calculate the number of tuple elements.
3max(tuple)
Returns the maximum value of the element in the tuple.
4min(tuple)
Returns the minimum value of the element in the tuple.
5tuple(seq)
Convert the list to a tuple.

Dictionary built-in functions & methods

Python dictionary contains the following built-in functions:

Serial numberFunction and description
1cmp(dict1, dict2)
Compares two dictionary elements.
2len(dict)
Calculate the number of dictionary elements, that is, the total number of keys.
3str(dict)
Output the printable string representation of the dictionary.
4type(variable)
Returns the input variable type. If the variable is a dictionary, returns the dictionary type.

Python dictionary contains the following built-in methods:

Serial numberFunction and description
1radiansdict.clear()
Delete all elements in the dictionary
2radiansdict.copy()
Return a dictionary Copy
3radiansdict.fromkeys()
Create a new dictionary, using the elements in the sequence seq as the keys of the dictionary, and val is the value corresponding to all keys in the dictionary Initial value
4radiansdict.get(key, default=None)
Returns the value of the specified key, if the value is not in the dictionary, returns the default value
5radiansdict.has_key(key)
Returns true if the key is in the dictionary dict, otherwise returns false
6radiansdict.items()
Returns a traversable (key, value) tuple array as a list
7radiansdict. keys()
Returns all the keys of a dictionary in a list
8radiansdict.setdefault(key, default=None)
and get() Similar, but if the key does not exist in the dictionary, the key will be added and the value will be set to default
9radiansdict.update(dict2)
Put The key/value pairs of dictionary dict2 are updated into dict
10radiansdict.values()
Return all values ​​in the dictionary as a list

Python 日期和时间

thon 程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。

Python 提供了一个 time 和 calendar 模块可以用于格式化日期和时间。

时间间隔是以秒为单位的浮点小数。

每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。

Python 的 time 模块下有很多函数可以转换常见日期格式。如函数time.time()用于获取当前时间戳, 如下实例:


#!/usr/bin/python# -*- coding: UTF-8 -*-import time;  # 引入time模块ticks = time.time()print "当前时间戳为:", ticks
Copy after login

以上实例输出结果:

当前时间戳为: 1459994552.51
Copy after login

时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。


什么是时间元组?

很多Python函数用一个元组装起来的9组数字处理时间:

Serial numberFieldValue
04-digit year 2008
1month1 to 12
21 to 31
3hours0 to 23
4Minutes0 to 59
5Seconds0 to 61 (60 or 61 is a leap second)
6Day of the week0 to 6 (0 is Monday)
7Day of the year1 to 366 (Julian calendar)
8 Daylight Saving Time-1, 0, 1, -1 is the flag to determine whether it is daylight saving time

The above is the struct_time tuple. This structure has the following properties:

Serial numberAttributeValue
0tm_year 2008
1tm_mon1 to 12
2tm_mday1 to 31
3tm_hour0 to 23
4tm_min0 to 59
5tm_sec0 to 61 ( 60 or 61 is a leap second)
6tm_wday0 to 6 (0 is Monday)
7tm_yday1 to 366 (Julian calendar)
8tm_isdst-1, 0, 1, -1 are flags to determine whether it is daylight saving time

获取当前时间

从返回浮点数的时间辍方式向时间元组转换,只要将浮点数传递给如localtime之类的函数。

#!/usr/bin/python# -*- coding: UTF-8 -*-import time

localtime = time.localtime(time.time())print "本地时间为 :", localtime
Copy after login

以上实例输出结果:

本地时间为 : time.struct_time(tm_year=2016, tm_mon=4, tm_mday=7, tm_hour=10, tm_min=3, tm_sec=27, tm_wday=3, tm_yday=98, tm_isdst=0)
Copy after login

获取格式化的时间

你可以根据需求选取各种格式,但是最简单的获取可读的时间模式的函数是asctime():

#!/usr/bin/python# -*- coding: UTF-8 -*-import time

localtime = time.asctime( time.localtime(time.time()) )print "本地时间为 :", localtime
Copy after login

以上实例输出结果:

本地时间为 : Thu Apr  7 10:05:21 2016
Copy after login

格式化日期

我们可以使用 time 模块的 strftime 方法来格式化日期,:

time.strftime(format[, t])
Copy after login
#!/usr/bin/python# -*- coding: UTF-8 -*-import time# 格式化成2016-03-20 11:45:39形式print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 格式化成Sat Mar 28 22:24:24 2016形式print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) 
  # 将格式字符串转换为时间戳a = "Sat Mar 28 22:24:24 2016"print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
Copy after login

以上实例输出结果:

2016-04-07 10:25:09Thu Apr 07 10:25:09 20161459175064.0
Copy after login

python中时间日期格式化符号:

  • %y 两位数的年份表示(00-99)

  • %Y 四位数的年份表示(000-9999)

  • %m 月份(01-12)

  • %d 月内中的一天(0-31)

  • %H 24小时制小时数(0-23)

  • %I 12小时制小时数(01-12)

  • %M 分钟数(00=59)

  • %S 秒(00-59)

  • %a 本地简化星期名称

  • %A 本地完整星期名称

  • %b 本地简化的月份名称

  • %B 本地完整的月份名称

  • %c 本地相应的日期表示和时间表示

  • %j 年内的一天(001-366)

  • %p 本地A.M.或P.M.的等价符

  • %U 一年中的星期数(00-53)星期天为星期的开始

  • %w 星期(0-6),星期天为星期的开始

  • %W 一年中的星期数(00-53)星期一为星期的开始

  • %x 本地相应的日期表示

  • %X 本地相应的时间表示

  • %Z 当前时区的名称

  • %% %号本身


获取某月日历

Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历:

#!/usr/bin/python# -*- coding: UTF-8 -*-import calendar

cal = calendar.month(2016, 1)print "以下输出2016年1月份的日历:"print cal;
Copy after login

以上实例输出结果:

以下输出2016年1月份的日历:
    January 2016Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 1011 12 13 14 15 16 1718 19 20 21 22 23 2425 26 27 28 29 30 31
Copy after login

Time 模块

Time 模块包含了以下内置函数,既有时间处理相的,也有转换时间格式的:

Serial number Function and description
1 time.altzone
Return to Greenway The offset in seconds for the western daylight saving time zone. Negative values ​​are returned if the area is east of Greenwich (such as Western Europe, including the UK). Available only in regions where daylight saving time is enabled.
2 time.asctime([tupletime])
Accepts a time tuple and returns a readable form of "Tue Dec 11 18:07: 14 2008" (Tuesday, December 11, 2008 18:07:14) is a 24-character string.
3 time.clock( )
Returns the current CPU time in seconds calculated as a floating point number. It is used to measure the time consumption of different programs and is more useful than time.time().
4 time.ctime([secs])
The function is equivalent to asctime(localtime(secs)). No parameters are given, which is equivalent to asctime()
5 time.gmtime([secs])
Receives the timeout (the number of floating point seconds elapsed since the 1970 epoch) and returns Greenwich astronomical time The time tuple under t. Note: t.tm_isdst is always 0
6 time.localtime([secs])
Receive time (floating point seconds elapsed after 1970 epoch number) and returns the time tuple t in local time (t.tm_isdst can be 0 or 1, depending on whether the local time is daylight saving time).
7 time.mktime(tupletime)
Accepts a time tuple and returns the timeout (the number of floating point seconds elapsed since epoch 1970).
8 time.sleep(secs)
Delay the running of the calling thread, secs refers to the number of seconds.
9 time.strftime(fmt[,tupletime])
Receives a time tuple and returns the local time as a readable string in a format determined by fmt.
10 time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
According to The format of fmt parses a time string into a time tuple.
11 time.time( )
Returns the timestamp of the current time (the number of floating-point seconds elapsed since epoch 1970).
12 time.tzset()
Reinitialize time-related settings according to the environment variable TZ.

The Time module contains the following two very important attributes:

Serial Number Attribute And description
1 time.timezone
The property time.timezone is the local time zone (without daylight saving time) distance from Greenwich Offset seconds (>0, Americas; <=0 most of Europe, Asia, Africa).
2 time.tzname
The attribute time.tzname contains a pair of strings that vary depending on the situation, namely The local time zone name with and without daylight saving time.

Calendar module

The functions of this module are all calendar-related, such as printing the character calendar of a certain month.

Monday is the default first day of the week, and Sunday is the default last day. To change the settings, you need to call the calendar.setfirstweekday() function. The module contains the following built-in functions:

Serial number Function and description
1 calendar.calendar(year, w=2,l=1,c=6)
Returns a year calendar in multi-line string format, with 3 months per line and an interval of c. Daily width interval is w characters. The length of each line is 21* W+18+2* C. l is the number of lines per week.
2 calendar.firstweekday( )
Returns the setting of the current weekly starting day. By default, 0 is returned when the caendar module is first loaded, which is Monday.
3 calendar.isleap(year)
returns True if it is a leap year, otherwise false.
4 calendar.leapdays(y1,y2)
Returns the total number of leap years between Y1 and Y2.
5 calendar.month(year,month,w=2,l=1)
Returns a multi-line string The calendar format is year and month, with two rows of titles and one row for each week. Daily width interval is w characters. The length of each line is 7* w+6. l is the number of lines per week.
6 calendar.monthcalendar(year,month)
Returns a single-level nested list of integers. Each sublist holds an integer representing a week. Dates outside Year, month, and month are all set to 0; days within the range are represented by the day of the month, starting from 1.
7 calendar.monthrange(year,month)
Returns two integers. The first is the date code of the day of the week of the month, and the second is the day code of the month. Days range from 0 (Monday) to 6 (Sunday); months range from 1 to 12.
8 calendar.prcal(year,w=2,l=1,c=6)
is equivalent to print calendar .calendar(year,w,l,c).
9 ##calendar.prmonth(year,month,w=2,l=1) Equivalent to print calendar.calendar(year, w, l, c).
10 calendar.setfirstweekday(weekday)
Set the starting day code of each week. 0 (Monday) to 6 (Sunday).
11 calendar.timegm(tupletime)
The opposite of time.gmtime: accepts a time tuple form and returns the time The time of day (the number of floating point seconds elapsed since the 1970 epoch).
12 calendar.weekday(year,month,day)
Returns the date code of the given date. 0 (Monday) to 6 (Sunday). Months range from 1 (January) to 12 (December).

Other related modules and functions

In Python, other modules for processing dates and times are:

  • datetime module

  • pytz module

  • dateutil module

The above is the detailed content of Python basic syntax encyclopedia. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template