1、将字符串的时间"2017-10-10 23:40:00"转换为时间戳和时间元组
import time s="2017-10-10 23:40:00" stru_time=time.strptime(s,"%Y-%m-%d %H:%M:%S") c_time=time.mktime(stru_time) print(stru_time,c_time)
2、字符串格式更改。如提time = “2017-10-10 23:40:00”,想改为 time= “2017/10/10 23:40:00”
import time s= "2017-10-10 23:40:00" stru_time=time.strptime(s,"%Y-%m-%d %H:%M:%S") s1=time.strftime("%Y/%m/%d %H:%M:%S",stru_time) print(s1)
3、获取当前时间戳转换为指定格式日期
import time now_time=time.time() stru_time=time.localtime(now_time) for_time=time.strftime("%Y-%m-%d %H:%M:%S",stru_time) print(for_time)
4、获得三天前的时间
import time t1=time.time()-60*60*24*3 stru_time=time.localtime(t1) for_time=time.strftime("%m/%d/%Y %H:%M:%S",stru_time) print(for_time)
5、求时间差
import time t1="1993-12-27" stru_time=time.strptime(t1,"%Y-%m-%d") c_time=time.mktime(stru_time) t=time.time()-c_time st_time=time.gmtime(t) print("相差%s年%s月%s天%s小时%s分钟%s秒"%(st_time.tm_year-1970,st_time.tm_mon-1,st_time.tm_mday-1,st_time.tm_hour,st_time.tm_min,st_time.tm_sec))
6、随机验证码
yzm="" a=range(65,91) b=range(48,58) li=list(a)+list(b) count=0 while count<6: s=random.choice(li) yzm+=chr(s) count+=1 print(yzm) import random def v_code(): code = '' for i in range(5): num=random.randint(0,9) alf=chr(random.randint(65,90)) add=random.choice([num,alf]) code="".join([code,str(add)]) return code print(v_code()) 随机验证码