time模块
%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %a Locale's abbreviated weekday name. %A Locale's full weekday name. %b Locale's abbreviated month name. %B Locale's full month name. %c Locale's appropriate date and time representation. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM.
import time
print('1' * 20)
time.sleep(2) # 延迟时间
print('2' * 10)
print(time.time()) # 秒时间戳1978年的凌晨到现在的秒数
print(time.localtime()) # 默认是本地时间
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())) # 接收以时间元组,并返回可读字符串表示的当地时间,格式由参数format决定
import datetime
print(datetime.datetime.now()) #获取当前时间
'''
计算七天前的时间日期
'''
res = datetime.datetime.now() - datetime.timedelta(days=7)
print(res)
random模块
print(random.random())
# [0,10)
print(random.random() * 10)
print(random.randint(1, 10)) # 随机整数,全闭区间
li = list('135')
print(random.choice(li)) # choice 选择 随机在序列中取一个元素
li = (1, 2, 3, 4, 5, 6)
# random.shuffle(li) #列表可使用
print(random.sample(li, 2)) # 随机取指定个数的值,返回的数据是列表
# print(li)
# random.randrange()
print(random.randrange(1, 10, 2)) # 左闭右开,从randrange随机选取一个数
'''
1.验证码6位数 2.全部为数字
for 强转 range if while append 列表 random
'''
def v_code():
code = ''
for i in range(6):
add_num = random.randint(0, 9)
code += str(add_num)
print(code)
v_code()
'''
字母加数字组成 randrange(65,91)--65--A
'''
print(ord('A'))
print(chr(65))
def v_code():
code = ''
for i in range(6):
add_num = random.randint(0, 9)
chr_num = chr(random.randrange(65, 91))
li = [add_num, chr_num]
# code += str(add_num) + chr_num
num = random.choice(li)
code += str(num)
print(code)
v_code()
json模块
json.loads() # json转化为字典(适用于语句)
json.dumps() # 字典转为json(适用于语句)
json.load() #
json.dump() #
import json
a = "python" # str
b = {"name": "python"} # dict
d = '{"name":"python"}' # Json数据
print(type(b)) # <class 'str'>
# data = {'name':'zs'}
# print(type(data))
# #dict-str
# res = str(data)
# print(res)
# print(type(res))
# res = json.dumps(data)
# print(res)
# print(type(res))
# json数据
#18
j_data = '{"age":18}' #str 通过索引,切片 json格式数据
j_data = json.loads(j_data)
num = j_data['age']
print(num)
包
导入包的方法
~from 包名 import 模块名
~from 包名 import * ----->模块名.方法()访问,用_all_暴露接口
~import 包名 ---->用包名.模块名.方法名()访问,需要import .import demo,demo1
__init__.py 创建包自带,控制包导入行为
__all__=['包1','包2']------>from 包名 import *
from.import 模块名 ------>import 包名
程序主入口
一个.py除了可以被直接运行外,还可以作为模块,被其他.py文件导入。不管是直接运行还是被导入,.py文件的最顶层代码都会被运行(Python用缩进来区分代码层次)。
但是当一个.py文件作为模块导入时,我们可能不希望一部分代码被运行。那么就可以将这部分代码调用写在程序中。