The most complete history python face questions explain (a) (with detailed answers

1, briefly interpreted and compiled programming language?

concept:

  • Compiled language: to do all of the source code compiled into binary code that can run the program. Then, you can run the program directly.
  • Interpreted language: to do a translation of the source, and then do one, until the end!

the difference:

  • Compiled language, execution speed, high efficiency; compiler dependent, cross-platform hearing. Such as C, C ++, Delphi, Pascal, Fortran.
  • Interpreted language, perform slow and inefficient; dependence interpreter, cross-platform is good. Such as Java, Basic.

2, Python interpreter type and characteristics

  • CPython
    • Use c language to develop the broadest interpreter
  • IPython
    • Based on an interactive timer interactively over the same cpython enhancements and cpython
  • PyPy
    • The goal is the efficiency of the use of JIT techniques for dynamically compiled python code, improve the efficiency
  • JPython
    • Java interpreter running on the python code directly compiled into Java bytecode execution
  • IronPython
    • Interpreter running on the Microsoft .NET platform, the python compiled. NET bytecode

3, python common specification PEP8

  • Each level indented with 4 spaces
  • Python 3 does not allow mixed use Tab and spaces to indent.
  • Restrictions on all lines of the maximum line width of 79 characters.
  • You should always use the code in the core Python distribution of UTF-8 (ASCII in Python 2).
  • Recommended introduced absolute path, because they are usually more readable

 4, to achieve the following binary code conversion by:

hex()
转换一个整数对象为十六进制的字符串

>>> hex(16)
'0x10'
>>> hex(18)
'0x12'
>>> hex(32)
'0x20'
oct()
转换一个整数对象为八进制的字符串

>>> oct(8)
'0o10'
>>> oct(166)
'0o246'
bin()
转换一个整数对象为二进制字符串

>>> bin(10)
'0b1010'
>>> bin(255)
'0b11111111'
chr()
转换一个[0, 255]之间的整数为对应的ASCII字符

>>> chr(65)
'A'
>>> chr(67)
'C'
>>> chr(90)
'Z'
>>> chr(97)
'a'
ord()
将一个ASCII字符转换为对应整数

>>> ord('A')
65
>>> ord('z')
122
16进制转10进制
>>> int('10', 16)
16
>>> int('0x10', 16)
16

8进制转10进制
>>> int('0o10', 8)
8
>>> int('10', 8)
8

2进制转10进制
>>> int('0b1010', 2)
10
>>> int('1010', 2)
10

5, the maximum number of layers python recursion

import sys
sys.setrecursionlimit(100000)

def foo(n):
    print(n)
    n += 1
    foo(n)
        
if __name__ == '__main__':
    foo(1)

To get the maximum number of floating between 3925-3929, and this is computer related, otherwise it will not be a floating figure it out (emphasis on rigorous mathematical logic)

6, the ternary operator rules and scenarios

  •         Ternary operator assignment is when a variable to be added directly determined and then assigned
  •         Ternary operator functions consistent with 'if .... else' statement process, writing it in a row, the code is very refined, more efficiency
  •         格式:[on_true] if [expression] else [on_false]
  •         res = value 2 value 1 if the condition else

7, include a difference Python2 and Python3

  • print  
  • input
问题:如何获取编码方式的信息?
获取目标bytes的编码方式
这一情况可以通过chardet模块的detect()函数来获取信息,chardet是第三方库,可以通过pip来安装

b是待检测的bytes变量

import chardet
print(chardet.detect(b))
######output####
 {'confidence': 1.0, 'encoding': 'ascii'}
1
2
3
4
5
confidence是指匹配程度,encoding是指可能的编码方式

获取当前环境的编码方式 
这一情况可以使用sys模块下的getdefaultencoding()函数来获取信息

import sys
print(sys.getdefaultencoding())

######## output#####
utf-8
  • What problems on the console to see in the end is
写上面的东西的时候产生了一个疑问,现在已经知道Python内部存储str的方式是使用unicode字符集,但是我们在屏幕上看到的并不是unicode字符集
s = "你好"
print(s)
#########output#############
你好
s的 unicode 是 \u4f60\u597d
1
那么,这中间应该是进行了某种转换 
实际上,在执行print(str)的时候,python内部执行了encoding操作,控制台拿到的其实是一个bytes变量 
之后,控制台又根据环境内部的编码方式,将所得到的bytes内容进行decoding的操作,就显示了原先str的内容
  • Open the file is no longer supported file method, can only open 
  • range no longer return to the list, but an iterative target range
  • Division / is not divisible, but give float, double slash // need divisible
  • urllib and urllib2 merged into urllib, commonly used urllib2.urlopen () becomes urllib.request.urlopen ()
  • There are large string and encoding related changes, is simply the original str become the new bytes, the original unicode into a new str.

8 difference, xrange and range of

  python2 xrange usage and in exactly the same range, the difference is not generated a list object, but a generator.

9、python的read() 、readline()、readlines()、xreadlines()

  • read () reads the entire file, reads the contents of the file into a string variable in the end, return type str.
  • the readline () to read single line, into a string variable, str return type.
  • readlines () to read all the contents of the file, according to the behavior of the unit into a list and return type list.
  • the xreadlines () Returns a generator, to operate the file for each line cycle.

10, include a common Boolean value of False

  None、""、0、[]、()、{}

11, strings, lists, tuples, each commonly used dictionaries five methods (integer, floating point, string, boolean, list of tuples, dictionaries, set date)

String:

# encoding:utf-8
__author__ = 'Fioman'
__date__ = '2018/11/19 15:10'

# 1. 去掉空格和特殊符号
name = " abcdefgeyameng  "
name1 = name.strip()  # 并不会在原来的字符串上操作,返回一个去除了两边空白的字符串
print(name1, len(name1), name, len(name))
# abcdefgeyameng 14  abcdefgeyameng   17

# 去掉左边的空格和换行符
name2 = name.lstrip()
print(name2, len(name2))# print(name2, len(name2))#

# 去掉右边的空格和换行符
name3 = name.rstrip()
print(name3, len(name3)) # abcdefgeyameng 15


# 2.字符串的搜索和替换
name.count('e')  # 查找某个字符在字符串中出现的次数
name.capitalize() # 首字母大写
name.center(100,'-') # 把字符串方中间,两边用-补齐,100表示占位多少
name.find('a') # 找到这个字符返回下标,多个时返回第一个,不存在时返回-1
name.index('a') # 找到这个字符返回下标,多个时返回第一个,不存在时报错
print(name.replace(name,'123')) # 字符串的替换
name.replace('abc','123') # 注意字符串的替换的话,不是在原来的字符串上进行替换.而是返回一个替换后的字符串.

# 3.字符串的测试和替换函数
name.startswith("abc") # 是否以abc开头
name.endswith("def") # 是否以def结尾
name.isalnum() # 是否全是字母和数字,并且至少包含一个字符
name.isalpha() # 是否全是字母,并至少包含一个字符
name.isdigit() # 是否全是数字,并且至少包含一个字符
name.isspace() # 是否全是空白字符,并且至少包含一个字符
name.islower() # 是否全是小写
name.isupper() # 是否全是大写
name.istitle() # 是否是首字母大写

# 4.字符串的分割
name.split('') # 默认按照空格进行分隔,从前往后分隔
name.rsplit() # 从后往前进行分隔

# 5.连接字符串
'.'.join(name) # 用.号将一个可迭代的序列拼接起来

name = 'geyameng'
# 6.截取字符串(切片)
name1 = name[0:3] # 第一位到第三位的字符,和range一样不包含结尾索引
name2 = name[:] # 截取全部的字符
name3 = name[6:] # 截取第6个字符到结尾
name4 = name[:-3] # 截取从开头到最后一个字符之前
name5 = name[-1] # 截取最后一个字符
name6 = name[::-1] # 创造一个与原字符串顺序相反的字符串
name7 = name[:-5:-1] # 逆序截取

List:

# encoding:utf-8
__author__ = 'Fioman'
__date__ = '2018/11/19 16:26'

# 1.创建一个列表
list1 = ['1', '2', '3', '4']
list2 = list("1234")
print(list1, list2)
print(list1 == list2)
# 以上创建的两个列表是等价的,都是['1', '2', '3', '4']

# 2.添加新元素
# 末尾追加
a = [1, 2, 3, 4, 5]
a.append(6)
print(a)

# 指定位置的前面插入一个元素
a.insert(2, 100)  # 在下标为2的前面插入一个元素100
print(a)

# 扩展列表list.extend(iterable),在一个列表上追加一个列表
a.extend([10, 11, 12])
print(a)

# 3.遍历列表
# 直接遍历
for i in a:
    print(i)

# 带索引的遍历列表
for index, i in enumerate(a):
    print(i, index)

# 4.访问列表中的值,直接通过下标取值.list[index]
print(a[2])

# 从list删除元素
# List.remove() 删除方式1:参数object 如果重复元素,只会删除最靠前的.
a = [1,2,3]
a.remove(2) # 返回值是None

# List.pop()  删除方式2:pop 可选参数index,删除指定位置的元素 默认为最后一个元素
a = [1,2,3,4,5]
a.pop()
print(a)

a.pop(2)
print(a)

# 终极删除,可以删除列表或指定元素或者列表切片,list删除后无法访问
a = [1,2,3,4,5,6]
del  a[1]
print(a) # 1, 3, 4, 5, 6]

del a[1:]
print(a) # 1

del a
# print(a) # 出错,name a is not defined


# 排序和反转代码
# reverse 反转列表
a = [1,2,3,4,5]
a.reverse()
print(a)

# sort 对列表进行排序,默认升序排列.有三个默认参数cmp = None,key = None,reverse = False

# 7.Python的列表的截取与字符串操作类型相同,如下所示
L = ['spam','Spam','SPAM!']
print(L[-1]) # ['SPAM']

# 8.Python列表操作的函数和方法
len(a)  # 列表元素的个数
max(a)  # 返回列表元素最大值
min(a)  # 返回列表元素最小值
list(tuple) #将一个可迭代对象转换为列表

# 列表常用方法总结
a.append(4)
a.count(1)
a.extend([4,5,6])
a.index(3)
a.insert(0,2)
a.remove()
a.pop()
a.reverse()
a.sort()

Tuple:

1. iterable generate a tuple 
    T = tuple ( 'abc')

Tuple sort
noted
when tuples sort usually come and converts it to a list makes it a variable object. Sorted method or use, it receives any sequence object.

T = ('c','a','d','b')
tmp = list(T)
tmp.sort()  ==> ['a','b','c','d']
T = tunple(tmp)
sorted(T)

dictionary:

以下实例展示了 fromkeys()函数的使用方法:

实例(Python 2.0+)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq)
print "新字典为 : %s" % str(dict)
dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" % str(dict)
以上实例输出结果为:

新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}
Construction dictionary by zip function 
D = dict (zip (keyslist, valueslist))
By assignment expression dictionary configured tuple (key must be a string, the string because if not, the configuration of the processing time will be treated as a string) 
D = dict (name = 'Bob', Age 42 is =) ==> { 'name': 'Bob,' age ': 42}
List all keys, values obtained is noted that an iterative object rather than a listing with the time to be converted.. 
D.keys ()     
D.values ()   
D.items () -> key + value
Delete dictionary (according to the key) and a length 
D.pop (Key)     
len (D) 
del D [Key]
Add or modify the value of the key corresponding to 
D [key] = value # key already exists, if modified, created if it does not exist.
Dictionary derivation 
D = [x: x ** 2 for x in range (10) if x% 2 == 0]

 12, lambda expression format and application scenarios

1, lambda functions in conjunction with the use list

list = lambda:x for x in range(10)
print (list[0])
>>>9

list = lambda x:x for x in range(10)
print (list[0])
>>>0

2, map, filter, reduce the function

例子:
a = [('a',1),('b',2),('c',3),('d',4)]
a_1 = list(map(lambda x:x[0],a))
如上例子,map函数第一个参数是一个lambda表达式,输入一个对象,返回该对象的第一个元素。第二个就是需要作用的对象,此处是一个列表。Python3中map返回一个map对象,我们需要人工转为list,得到的结果就是[‘a’,’b’,’c’,’d’] 
例子:
a = [1,2,3,4]
b = [2,3,4,5]
a_1 = list(map(lambda x,y:x+y,a,b))
上边这个例子是为了说明,lambda表达式参数可以是多个。返回结果是[3,5,7,9]

Examples:
a = [1,2,3,4,5,6,7]
A_1 = filter (lambda X: X <4, a)
as an example, the definition of the lambda expression, the screening elements 4 is less than a list of results to [1,2,3]. filter function directly returns a list, no longer need to be converted, and the third is the initial value, two elements we did not give an initial value, that is, before the start of the operation of the two sequences. Otherwise, the initial value of the first element and the sequence of operation of our analysis, and then the result of the third operation element, and so on. The result is the example 28

Examples:
from functools reduce # Import module to be imported to python3
A = [1,2,3,4,5,6,7]
A_1 reduce =: (the lambda X, Y X + Y, A)
the lambda expression reduce use type requires two parameters, reduce the function a total of three parameters,
the first is that a lambda expression, and the second is to cumulative sequence, and the third is the initial value,
we did not give an initial value, then the start of the operation of two the first two elements of that sequence. Doing so will
use the first element and the initial value of the sequence given in our operation, and then the result of the third element operation
for, and so on. The result is the example 28

3, multi-criteria sort dictionary

例子:
dict = {'a':1,'b':2,'c':3,'d':4,'e':3,'f':1,'g':7}
sorted_dict_asc = sorted(dict.items(),key=lambda item:item[0])
sorted_dict_dsc = sorted(dict.items(),key=lambda item:item[0],reverse=True)

Output (first ascending, descending second):
[( 'A',. 1), ( 'B', 2), ( 'C',. 3), ( 'D',. 4), ( 'E' ,. 3), ( 'F',. 1), ( 'G',. 7)]
[( 'G',. 7), ( 'F',. 1), ( 'E',. 3), ( 'D', 4), ( 'c', 3), ( 'b', 2), ( 'a', 1)]]

13, pass effect

  placeholder is an empty sentence pass, in order to maintain the integrity of the program structure.

14, * arg and ** kwarg role

When you define a function, use and ** kwarg * arg
* arg and ** kwarg can help us deal with this situation above, it allows us to pass multiple arguments when calling function
def exmaple2 (required_arg, * arg, ** kwarg ):
    IF Arg:
        Print "Arg:", Arg

    if kwarg:
        print "kwarg: ", kwarg

exmaple2 ( "the Hi",. 1, 2,. 3, keyword1 = "bar", keyword2 = "foo")
>> Arg: (. 1, 2,. 3)
>> kwarg: { 'keyword2': 'foo', 'keyword1 ':' bar '}
can be seen from the above example, when I pass more arguments when
* arg put extra positional parameters into a tuple
** kwarg put into keyword argument dict

15, the difference is and ==

  • Python three basic elements contained in the object, are: id (identity), type (data type) and value (value).
  • == python is the standard operators in comparison operator for comparing two objects of determination value (value) is equal to
  • is also known as the identity operator , the operator determines that the comparison between the object unique identifier, i.e. whether the same id.

    Only in the case of numeric and string, a is b it is True, when a and b are tuple, list, dict or set type, a is b is False.

16, and the depth of the copy application scenarios outlined Python

Usage depth from the copy module copies.

Import modules: import copy

Shallow copy: copy.copy

Deep copy: copy.deepcopy

  For numbers and strings, assignment, deep and shallow copy copy meaningless, because it always points to the same memory address.

  Literally: shallow copy means copying only the data set of the first layer, all the layers deep copy means copies the data set. So for the collection of data for only one layer of meaning is the same as the depth of copies, such as strings, numbers, there is only one dictionary, lists, tuples and so on.

  Dictionary (list) copy of shades

    Assignment:

import copy
n1 = {'k1':'wu','k2':123,'k3':['alex',678]}
n2 = n1

 

Shallow copy:

import copy
n1 = {'k1':'wu','k2':123,'k3':['alex',678]}
n3 = copy.copy(n1)

 

Deep copy:

import copy
n1 = {'k1':'wu','k2':123,'k3':['alex',678]}
n4 = copy.deepcopy(n1)

  深拷贝的时候python将字典的所有数据在内存中新建了一份,所以如果你修改新的模版的时候老模版不会变。相反,在浅copy 的时候,python仅仅将最外层的内容在内存中新建了一份出来,字典第二层的列表并没有在内存中新建,所以你修改了新模版,默认模版也被修改了。

17、Python是如何进行内存管理的

 

答:从三个方面来说,一对象的引用计数机制,二垃圾回收机制,三内存池机制

 

一、对象的引用计数机制

 

Python内部使用引用计数,来保持追踪内存中的对象,所有对象都有引用计数。

 

引用计数增加的情况:

 

1,一个对象分配一个新名称

 

2,将其放入一个容器中(如列表、元组或字典)

 

引用计数减少的情况:

 

1,使用del语句对对象别名显示的销毁

 

2,引用超出作用域或被重新赋值

 

Sys.getrefcount( )函数可以获得对象的当前引用计数

 

多数情况下,引用计数比你猜测得要大得多。对于不可变数据(如数字和字符串),解释器会在程序的不同部分共享内存,以便节约内存。

 

二、垃圾回收

 

1,当一个对象的引用计数归零时,它将被垃圾收集机制处理掉。

 

2,当两个对象a和b相互引用时,del语句可以减少a和b的引用计数,并销毁用于引用底层对象的名称。然而由于每个对象都包含一个对其他对象的应用,因此引用计数不会归零,对象也不会销毁。(从而导致内存泄露)。为解决这一问题,解释器会定期执行一个循环检测器,搜索不可访问对象的循环并删除它们。

 

三、内存池机制

 

Python提供了对内存的垃圾收集机制,但是它将不用的内存放到内存池而不是返回给操作系统。

 

1,Pymalloc机制。为了加速Python的执行效率,Python引入了一个内存池机制,用于管理对小块内存的申请和释放。

 

2,Python中所有小于256个字节的对象都使用pymalloc实现的分配器,而大的对象则使用系统的malloc。

 

3,对于Python对象,如整数,浮点数和List,都有其独立的私有内存池,对象间不共享他们的内存池。也就是说如果你分配又释放了大量的整数,用于缓存这些整数的内存就不能再分配给浮点数。

 

18、Python的可变类型和不可变类型

  • 数字、字符串、元组是不可变的,列表、字典是可变的。

对象池:

小整数对象池
[-5, 256] 这些小整数被定义在了一个整数对象池里,当引用小整数时会自动引用整数对象池里的对象,所以这些小整数不会重复创建,当多个变量指向同一个小整数时,实质上它们指向的是同一个对象。

字符串对象池
字符串对象是不可变对象,python有个intern机制,简单说就是维护一个字典,这个字典维护已经创建字符串(key)和它的字符串对象的地址(value),每次创建字符串对象都会和这个字典比较,没有就创建,重复了就用指针进行引用就可以了。intern机制处理字符串长度小于等于20且仅由数字字母下划线构成的,只创建一次。

19、列举常见的内置函数

数学相关

  • abs(a) : 求取绝对值。abs(-1)
  • max(list) : 求取list最大值。max([1,2,3])
  • min(list) : 求取list最小值。min([1,2,3])
  • sum(list) : 求取list元素的和。 sum([1,2,3]) >>> 6
  • sorted(list) : 排序,返回排序后的list。
  • len(list) : list长度,len([1,2,3])
  • divmod(a,b): 获取商和余数。 divmod(5,2) >>> (2,1)
  • pow(a,b) : 获取乘方数。pow(2,3) >>> 8
  • round(a,b) : 获取指定位数的小数。a代表浮点数,b代表要保留的位数。round(3.1415926,2) >>> 3.14
  • range(a[,b]) : 生成一个a到b的数组,左闭右开。 range(1,10) >>> [1,2,3,4,5,6,7,8,9]

类型转换

  • int(str) : 转换为int型。int('1') >>> 1
  • float(int/str) : 将int型或字符型转换为浮点型。float('1') >>> 1.0
  • str(int) : 转换为字符型。str(1) >>> '1'
  • bool(int) : 转换为布尔类型。 str(0) >>> False str(None) >>> False
  • bytes(str,code) : 接收一个字符串,与所要编码的格式,返回一个字节流类型。bytes('abc', 'utf-8') >>> b'abc' bytes(u'爬虫', 'utf-8') >>> b'\xe7\x88\xac\xe8\x99\xab'
  • list(iterable) : 转换为list。 list((1,2,3)) >>> [1,2,3]
  • iter(iterable): 返回一个可迭代的对象。 iter([1,2,3]) >>> <list_iterator object at 0x0000000003813B00>
  • dict(iterable) : 转换为dict。 dict([('a', 1), ('b', 2), ('c', 3)]) >>> {'a':1, 'b':2, 'c':3}
  • enumerate(iterable) : 返回一个枚举对象。
  • tuple(iterable) : 转换为tuple。 tuple([1,2,3]) >>>(1,2,3)
  • set(iterable) : 转换为set。 set([1,4,2,4,3,5]) >>> {1,2,3,4,5} set({1:'a',2:'b',3:'c'}) >>> {1,2,3}
  • hex(int) : 转换为16进制。hex(1024) >>> '0x400'
  • oct(int) : 转换为8进制。 oct(1024) >>> '0o2000'
  • bin(int) : 转换为2进制。 bin(1024) >>> '0b10000000000'
  • chr(int) : 转换数字为相应ASCI码字符。 chr(65) >>> 'A'
  • ord(str) : 转换ASCI字符为相应的数字。 ord('A') >>> 65

相关操作

  • eval() : 执行一个表达式,或字符串作为运算。 eval('1+1') >>> 2
  • exec() : 执行python语句。 exec('print("Python")') >>> Python
  • filter(func, iterable) : 通过判断函数fun,筛选符合条件的元素。 filter(lambda x: x>3, [1,2,3,4,5,6]) >>> <filter object at 0x0000000003813828>
  • map(func, *iterable) : 将func用于每个iterable对象。 map(lambda a,b: a+b, [1,2,3,4], [5,6,7]) >>> [6,8,10]
  • zip(*iterable) : 将iterable分组合并。返回一个zip对象。 list(zip([1,2,3],[4,5,6])) >>> [(1, 4), (2, 5), (3, 6)]
  • type():返回一个对象的类型。
  • id(): 返回一个对象的唯一标识值。
  • hash(object):返回一个对象的hash值,具有相同值的object具有相同的hash值。 hash('python') >>> 7070808359261009780
  • help():调用系统内置的帮助系统。
  • isinstance():判断一个对象是否为该类的一个实例。
  • issubclass():判断一个类是否为另一个类的子类。
  • globals() : 返回当前全局变量的字典。
  • next(iterator[, default]) : 接收一个迭代器,返回迭代器中的数值,如果设置了default,则当迭代器中的元素遍历后,输出default内容。
  • reversed(sequence) : 生成一个反转序列的迭代器。 reversed('abc') >>> ['c','b','a']

20、Python写9*9乘法表的两种简单方法

1 for i in range(1,10):
2     for j in range(1,i+1):
3         print("%s * %s = %s" %(j,i,i*j),end="")
4     print("")
print "\n".join("\t".join(["%s*%s=%s" %(x,y,x*y) for y in range(1, x+1)]) for x in range(1, 10))

21、如何安装第三方模块?以及用过哪些第三方模块?

  pip install 模块名

一、Python爬虫

1. 请求

requests(第三方模块)

2. 解析:

bs4(即beautifulsoup,第三方模块)

3. 储存:

pymongo(第三方模块):

  把数据写入MongoDB

MySQL-python(第三方模块):

  把数据写入MySQL里面。

协程:gevent(第三方模块)

二、Python数据分析&科学计算

numpy(第三方模块,C拓展):

  Copy了MATLAB的数据结构。很多数据分析和科学计算库的底层模块。提供了良好的数组数据结构和C拓展接口。

pandas(第三方模块,C拓展):

  Copy了R的data frame的数据结构。

22、常用模块都有那些?

import time
import datetime

print(time.asctime())      # 返回时间格式:Sun May  7 21:46:15 2017
print(time.time())         # 返回时间戳 ‘1494164954.6677325’
print(time.gmtime())       # 返回本地时间 的struct time对象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)
print(time.localtime())    # 返回本地时间 的struct time对象格式,time.struct_time(tm_year=2017, tm_mon=5, tm_mday=7, tm_hour=22, tm_min=4, tm_sec=53, tm_wday=6, tm_yday=127, tm_isdst=0)
print(time.gmtime(time.time()-800000))   # 返回utc时间的struc时间对象格式
print(time.asctime(time.localtime()))    # 返回时间格式Sun May  7 22:15:09 2017
print(time.ctime())                      # 返回时间格式Sun May  7 22:15:09 2017
print(time.strftime('%Y-%m-%d'))         #默认当前时间 2017-05-07
print(time.strftime('%Y-%m-%d',time.localtime())) #默认当前时间 2017-05-07

string_struct = time.strptime("2016/05/22","%Y/%m/%d") # 将日期字符串 转成 struct时间对象格式
print(string_struct)                     # 返回struct time对象格式 time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)

# 将日期字符串转成时间戳
struct_stamp = time.mktime(string_struct) # 将struct time时间对象转成时间戳
print(struct_stamp)                         # 返回时间戳 ‘1463846400.0’

# 将时间戳转为字符串格式
print(time.gmtime(time.time()-86640))         # 将utc时间戳转换成struct_time格式
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) # 将utc struct_time格式转成指定的字符串格式


# 时间加减
print(datetime.datetime.now())           # 返回当前时间 2017-05-07 22:36:45.179732
print(datetime.date.fromtimestamp(time.time()))  # 时间戳直接转换成日期格式 2017-05-07
print(datetime.datetime.now() + datetime.timedelta(3))    # 返回时间在当前日期上 +3 天
print(datetime.datetime.now() + datetime.timedelta(-3))    # 返回时间在当前日期上 -3 天
print(datetime.datetime.now() + datetime.timedelta(hours= 3)) # 返回时间在当前时间上 +3 小时
print(datetime.datetime.now() + datetime.timedelta(minutes= 30)) # 返回时间在当前时间上 +30 分钟

c_time  = datetime.datetime.now()
print(c_time)                          # 当前时间为 2017-05-07 22:52:44.016732
print(c_time.replace(minute=3,hour=2)) # 时间替换 替换时间为‘2017-05-07 02:03:18.181732’

print(datetime.timedelta)      # 表示时间间隔,即两个时间点之间的长度
print (datetime.datetime.now() - datetime.timedelta(days=5))  # 返回时间在当前时间上 -5 天

# python 日历模块
import calendar

print(calendar.calendar(theyear= 2017))     # 返回2017年整年日历
print(calendar.month(2017,5))               # 返回某年某月的日历,返回类型为字符串类型

calendar.setfirstweekday(calendar.WEDNESDAY) # 设置日历的第一天(第一天以星期三开始)
cal = calendar.month(2017, 4)
print (cal)

print(calendar.monthrange(2017,5))        # 返回某个月的第一天和这个月的所有天数
print(calendar.monthcalendar(2017,5))     # 返回某个月以每一周为元素的序列

cal = calendar.HTMLCalendar(calendar.MONDAY)
print(cal.formatmonth(2017, 5))           # 在html中打印某年某月的日历

print(calendar.isleap(2017))             # 判断是否为闰年
print(calendar.leapdays(2000,2017))       # 判断两个年份间闰年的个数
import random

# 随机数
print(random.random())              # 返回一个随机小数'0.4800545746046827'
print(random.randint(1,5))          # 返回(1-5)随机整型数据
print(random.randrange(1,10))       # 返回(1-10)随机数据

# 生成随机验证码
code = ''
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)
    code += str(temp)

print(code)

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_40925239/article/details/91354126