time模块用来打印时间,并且有暂停程序的功能,需要时间的地方就要调用。
时间戳表示的是从1970年1月1日0:00:00开始按秒计算的偏移量
import time
print(time.time())
1560166598.8710632
格式化时间就是普通字符串格式的时间表示方式,需要自己定义格式。
print(time.strftime('%Y-%m-%d'))
2019-06-10
print(time.localtime()) # 北京时间
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=10, tm_hour=19, tm_min=42, tm_sec=45, tm_wday=0, tm_yday=161, tm_isdst=0)
print(time.gmtime()) # 格林威治时间(时间标准时间)
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=10, tm_hour=11, tm_min=43, tm_sec=46, tm_wday=0, tm_yday=161, tm_isdst=0)
struct_time = time.localtime()
print(time.strftime('%Y-%m-%d',struct_time))
2019-06-10
print(time.mktime(struct_time))
1560167473.0
stamp_time = time.time()
print(time.localtime(stamp_time))
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=10, tm_hour=19, tm_min=55, tm_sec=25, tm_wday=0, tm_yday=161, tm_isdst=0)
print(time.strptime('2019-06-01 12:00:00','%Y-%m-%d %X'))
time.struct_time(tm_year=2019, tm_mon=6, tm_mday=1, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=152, tm_isdst=-1)
time.sleep(1)
datetime模块能进行时间的加减
import datetime
now = datetime.datetime.now()
print(now)
2019-06-10 20:05:05.697198
print(now + datetime.timedelta(3)) # 3代表的参数表示天数,且里面的参数只能是天,不能进行年和月的加减
print(now + datetime.timedelta(-3))
2019-06-13 20:06:34.748685
2019-06-07 20:09:11.633673
print(now.replace(year=2010,month=6,day=8,hour=19,minute=10,second=11))
2010-06-08 19:10:11.641058
print(random.random())
0.9112520136212495
打印[n,m]的整数 # 会去n和m
print(random.randint(1,5))
1
打印(n,m)的小数
print(random.uniform(1,5))
4.66308974253497
打印[n,m)的整数 取头不取尾
print(random.randrange(1,3))
1
### 从容器中随机选择一个(牢记,经常用) 抽奖程序就是基于这个基础做出来的
res = random.choices([1,4,7,9])
print(res)
[4]
抽奖实例:
count =0
while True:
res = random.choices([1000,22,333,44])
count +=500
if count == 3000:
print(f'恭喜你获得1000元大奖')
else:
if res ==1000:
print('再来一次!')
else:
print(f'恭喜你获得{res}')
print(random.sample([1,2,'w','t'],2))
[1, 'w']
lis = [1,2,3,4]
random.shuffle(lis)
print(lis)
[3, 1, 2, 4]
os模块与操作系统交互,在python中进行文件操作
查看当前文件路径 sys.argv() ==重点==
print(sys.argv)
['D:/pycharm学习笔记/test1/test-6-10.py']
获取解释器版本 sys.hexversion
print(sys.hexversion)
50726128
获取当前文件导入模块的路径 sys.path ==重点==
print(sys.path)
['D:\\pycharm学习笔记\\test1', 'D:\\pycharm学习笔记', 'D:\\python3\\python36.zip', 'D:\\python3\\DLLs', 'D:\\python3\\lib', 'D:\\python3', 'D:\\python3\\lib\\site-packages', 'D:\\pycharm\\PyCharm 2018.1.4\\helpers\\pycharm_matplotlib_backend']
从内存到硬盘这个过程叫做序列化,序列化必须得规定格式
特点:
with open('文件.json','w',encoding='utf8') as fw:
json.dump(dict,fw)
with open('文件.json','r',encoding='utf8') as fr:
data = json.load(fr)
pickle也是序列化和反序列化,json可以跨平台,只支持dict/list/str/int/float/bool/None
pickle支持python中任意数据类型,所以不能跨平台(不同平台的函数一定是不同的),pickle模块序列化过程是以==二进制==形式转换
with open('文件.json','wb') as fw:
pickle.dump(dict,fw)
with open('文件.json','rb') as fr:
data = pickle.load(fr)
原文:https://www.cnblogs.com/raynduan/p/11079149.html