time模块 & datetime模块 & 加密模块 & redis模块 & sql模块

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
####time模块
import time
#1.time.time()
#获取当前时间戳,从unix元年开始到现在过了多长时间 #时间戳转化为时间:百度搜索
print(time.time())
#打印:1510240706.2218175
#2.time.gmtime()
#获取标准时区的时间元组,时间戳转化为元组
print(time.gmtime())
#打印:time.struct_time(tm_year=2017, tm_mon=11, tm_mday=9, tm_hour=15, tm_min=18, tm_sec=26, tm_wday=3, tm_yday=313, tm_isdst=0)
#3.time.localtime()
#获取当前时区的时间元组
print(time.localtime())
#打印:time.struct_time(tm_year=2017, tm_mon=11, tm_mday=9, tm_hour=23, tm_min=18, tm_sec=26, tm_wday=3, tm_yday=313, tm_isdst=0)
#4.time.mktime()
#将时间元组转化为时间戳
today = time.localtime()
print(time.mktime(today))
#打印:1510240706.0
#5.格式化输出
print(time.strftime('%y%m%d %H%M%S'))
#打印:171109 231826
print(time.strftime('%Y%m%d %H%M%S'))
#打印:20171109 231826
print(time.strftime('%y-%m-%d %H:%M:%S'))#将时间元组转化为格式化输出的字符
#打印:17-11-09 23:18:26 此格式可采取
print(time.strftime('%Y-%m-%d %H:%M:%S'))
#打印:2017-11-09 23:18:26 此格式可采取
print(time.strftime('%Y-%M-%d %H:%M:%S'))
#打印:2017-18-09 23:18:26
print(time.strftime('%Y-%m-%D %H:%M:%S'))
#打印:2017-11-11/09/17 23:18:27
print(time.strftime('%Y-%m-%D %h:%M:%S'))
#打印:2017-11-11/09/17 Nov:18:26
print(time.strftime('%Y-%M-%D %H:%m:%S'))
#打印:2017-11-11/09/17 23:11:26
#print(time.strftime('%Y-%m-%D %H:%M:%s'))
#print(time.strptime(时间戳,格式)) #将时间戳转化为元组
print(time.strptime('123456789','%Y%m%d%H%M%S'))
#打印:time.struct_time(tm_year=1234, tm_mon=5, tm_mday=6, tm_hour=7, tm_min=8, tm_sec=9, tm_wday=5, tm_yday=126, tm_isdst=-1)
#print(time.strptime('123456789','%Y-%m-%d %H:%M:%S'))#报错,只能转化为'%Y%m%d%H%M%S'格式,再用格式化输出为其他格式
#6.time.sleep()
#线程等待时间
time.sleep(1)
#7.时间戳转化为指定格式输出
print('****时间戳--》时间元组--》格式化输出***')
t1 = time.time()#获取当前时间戳
t2 = time.gmtime(t1)#时间戳转化为元组
t3 = time.strftime('%Y-%m-%d',t2)#元组转化为格式化时间
print('t3={t3}'.format(t3=t3))
#打印:t3=2017-11-09
print(time.strftime('%Y-%m-%d',time.gmtime(int(time.time()))))

#时间戳转化为格式化时间输出方法
def transfer(timestamp,format='%Y-%m-%d %H:%M:%S'):
time_tuple = time.gmtime(timestamp)#时间戳转为时间元组
res = time.strftime(format,time_tuple)#时间元组转为时间格式化输出
print(res)
return res
transfer(123456789)
#打印:1973-11-29 21:33:09
transfer(123456789,'%Y-%m-%d')
#打印:1973-11-29

#格式化转化为时间戳输出方法
print('****格式化字符--》时间元组--》时间戳***')
def transfer2(time_str,format='%Y%m%d%H%M%S'):
time_tuple = time.strptime(time_str,format)#字符串转为时间元组
res = time.mktime(time_tuple)#时间元组转为时间戳
print(res)
return int(res)
transfer2('19731129213309')

####datetime模块
import datetime
#8.datetime.datetime.now()
#打印当前时间
now = datetime.datetime.now()
print(now)
#打印:2017-11-09 23:37:44.708079
#9.datetime.timedelta()
#向前或向后几天
print(datetime.datetime.now()+datetime.timedelta(3))#3天后
#打印:2017-11-12 23:37:44.708079
print(datetime.datetime.now()+datetime.timedelta(-3))#3天前
#打印:2017-11-06 23:37:44.708079
three_day = str(datetime.datetime.now()+datetime.timedelta(3))

# def get_other_time(day,format='%Y%m%d%H%M%S'):
# import datetime
# res = datetime.datetime.now() + datetime.timedelta(day)
# res_time = res.strftime((format()))
# print(res_time)
# return res_time
#
# get_other_time(1)

###加密模块
print('***加密模块***')
# #加密模块
#
s = 'jmy123'
new = 'jmy123'.encode()#str类型转化为bytes类型
print(type(s))
#打印:<class 'str'>
print(type(new))
#打印:<class 'bytes'>
print(s)
#打印:jmy123
print(s.encode())
#打印:b'jmy123'
new_s= new.decode()#bytes类型转化为str类型
print(type(new_s))
print(new_s)
###hashlib模块
#10.数据加密
import hashlib
md = hashlib.md5()#第1步:创建一个方法
#md.update('jay123')#报错:TypeError: Unicode-objects must be encoded before hashing
#md.update('123')#加密,报错:TypeError: Unicode-objects must be encoded before hashing。md.update()必须跟byte类型
md.update('jay123'.encode())#第二步:加密后转化为byte类型
print(md.digest())#第三步:加密后的数据,byte类型
#打印:b'\xf0\xe7\xd0\xd1|\xff\x89\x1e\xdb\xc9\xcd\xf9-\xcd\x92\x97'
print(md.hexdigest())#第三步:加密后的数据(32位)
#打印:f0e7d0d17cff891edbc9cdf92dcd9297
#
# #加密方法+加盐
# def md5_passwd(str,salt = '123456'):#salt为盐值,默认123456
# str = str + salt
# # start = '@#%$@'
# # end = '@#*&^%'
# # str = start + str + end
# print(str)
# import hashlib
# md = hashlib.md5()#构造一个MD5
# #md.update(str).encode()#语法错误
# md.update(str.encode())
# return md.hexdigest()
#
# print(md5_passwd('123456'))

print('***redis模块***')
# #redis是一个数据库,其数据全部是放在内存中的
# #每秒支持30w次的读写
#11.redis的操作
# import redis
#
# #连接数据库
# r = redis.Redis(host = '211.149.218.16',port = 6378,password = '123456',db=2)
#
# #添加key,写入内容
# r.set('test01','hello!')
#
# #获取key的value,打印byte类型
# print(r.get('test01')) #打印byte类型
# #打印:b'hello!'
#
# #获取key的value,打印string类型
# print(r.get('test01').decode())
# #打印:hello!
#
# #获取数据库r中的所有key
# print(r.keys())
# #打印:[b'test01', b'lxm', b'wll1', b's', b'wyf', b'yuanyuan', b'pst', b'duguanglong', b'xmh', b'\xe6\x9d\xa8\xe6\x99\x93\xe9\x92\xa2', b'yy', b'ylf', b'dwb', b'wjx', b'ssj', b'nhy', b'lhn', b'name', b'lzc', b'lsx', b'Dalei', b'zdq', b'ggy', b'a_ssj', b'txf', b'shenping', b'wll', b'ggg', b'jmy', b'lk', b'yxg', b'yj']
# # for k in r.keys():
# # print('{k}.{v}'.format(k=k.decode(),v=r.get(k).decode()))
# #print('{k}.{v}'.format(k=k.decode(), v=r.set(k,'111'))#有问题
#
# #向数据库test02中输入哈希值(key_value)
# r.hset('test04','age1','18')
# r.hset('test04','age2','18')
# r.hset('test04','age3','18')
# # r.hset('nhy1','age','18')
# #r.hget('nhy1','age')
#
# #获取test04中age1的value,打印byte类型
# print(r.hget('test04','age1'))
# #打印:b'18'
# #获取test04中age1的value,打印byte类型
# print(r.hget('test02','age1').decode())
# #打印:18
#
# #获取test02中所有的key&value
# print(r.hgetall('test02'))
# #打印:{b'age2': b'18', b'age1': b'18', b'age3': b'18', b'age': b'18'}
# #print(r.hgetall('test02').decode())#报错,字典不能加decode() AttributeError: 'dict' object has no attribute 'decode'
#
# #将bytes类型字典转化为str类型
# test = r.hgetall('test02')
# print(test)
# testdic = {}
# for i in test:
# testdic[i.decode()] = test[i].decode()
# print(testdic)
# print(r.type('test01'))#判断类型
# #打印:b'string'
# print(r.type('test02'))
# #打印:b'hash'
#
# #将db2迁移到db3
# #连接两个数据库
# #获取所有key-->判断key类型(r.type())--》.hgetall() .hset() .set()
# r1 = redis.Redis(host = '211.149.218.16',port = 6378,password = '123456',db=2)
# r2 = redis.Redis(host = '211.149.218.16',port = 6378,password = '123456',db=12)
# r1_key = r1.keys()
# for k in r2.keys():
# r2.delete(k)
# for k in r1_key:
# if r1.type(k)=='string'.encode():
# r2.set(k,r1.get(r1))
# else:
# hash_data = r1.hgetall(k)#获取hash类型的数据
# #print('r2_key: {r}'.format(r = r2_key))
# # for i in r2_key:
# # print(r1.hgetall(k))
# # print(r1[k][i])
# # r2.hset(k,i,r1.hget(k,i))
# for k2,v in hash_data.items():#循环刚才的数据获取到字典
# r2.hset(k,k2,v)

###12.SQL数据库操作
print('***sql***')
import pymysql
from pymysql.cursors import DictCursor #将数据转化为字典
#连接mysql
coon = pymysql.connect(host='211.149.218.16',port=3306,user='jxz',passwd='123456',db='jxz',charset='utf8')
#建立游标,仓库管理员
cur = coon.cursor()
cur1 = coon.cursor(DictCursor)
#定义sql
#insert_sql = 'insert into stu VALUE(11,"test01")'
#sql = 'select * from stu limit 3'
#sql = 'select * from stu limit 2,4'#从第3条,即下标为2的数据开始取值,取4条
sql = 'select * from stu limit 10'
#执行sql语句
cur.execute(sql)
cur1.execute(sql)
#cur.execute(insert_sql)
#获取sql执行的结果
res = cur.fetchall()
res1 = cur1.fetchall()
#coon.commit()#数据库更新时提交
print('res={res}'.format(res=res))
#打印:res=((1, 'updatetest'), (77, '哈哈,通通改了'), (109, '哈哈,通通改了'), (20171105, '谁动了我的数据'), (999, '哈哈,通通改了'), (11, '哈哈,通通改了'), (92, '哈哈,通通改了'), (999, '哈哈,通通改了'), (11, '哈哈,通通改了'), (66, '哈哈,通通改了'))
print('res1={res1}'.format(res1=res1))
#打印:res1=[{'id': 1, 'name': 'updatetest'}, {'id': 77, 'name': '哈哈,通通改了'}, {'id': 109, 'name': '哈哈,通通改了'}, {'id': 20171105, 'name': '谁动了我的数据'}, {'id': 999, 'name': '哈哈,通通改了'}, {'id': 11, 'name': '哈哈,通通改了'}, {'id': 92, 'name': '哈哈,通通改了'}, {'id': 999, 'name': '哈哈,通通改了'}, {'id': 11, 'name': '哈哈,通通改了'}, {'id': 66, 'name': '哈哈,通通改了'}]
print(res[0][1])
#打印:updatetest
print(res[1][1])
#打印:哈哈,通通改了

cur.execute(sql)
res1 = cur.fetchone()
res2 = cur.fetchone()
res3 = cur.fetchone()
print(res1)
#打印:(1, 'updatetest')
print(res2)
#打印:(77, '哈哈,通通改了')
print(res3)
#打印:(109, '哈哈,通通改了')

cur.execute(sql)
for c in cur:
print(c)

#执行SQL语句的方法
def op_mysql(host,user,passwd,db,sql,port=3306,charset='utf8'):
import pymysql
from pymysql.cursors import DictCursor
coon = pymysql.connect(host=host,user=user,passwd=passwd,db=db,charset=charset,port=port)
cur = coon.cursor(DictCursor)#指定返回类型
cur.execute(sql)
if (sql.strip()).startswith('select') :
res = cur.fetchall()
else:
coon.commit()#更新数据库时提交
res = 'ok'
cur.close()
coon.close()
print(res)
return res
sql1 = 'insert into stu VALUE(111,"测试加入")'
sql2 = 'update stu set name="测试加入00" where id=1'
sql3 = 'delete from stu where id=89'
sql4 = 'select id,name from stu where id =1;'

#作业:写一个随机生成身份证号的程序,自己查身份证规则,输入多少产生多少条--》吧产生的数据写到redis中名字 身份证号,hash类型
#环境变量写到setting中,调用里面的环境变量
#商品信息和用户信息存到数据库中,改写shop系统,
#user 表 id username password money role
# product表 id pname price

posted on 2017-11-16 23:25  yezi_396  阅读(234)  评论(0编辑  收藏  举报

导航