常用模块(一)
一、时间(time)模块
时间戳 (Timestamp):时间戳表示的是从1970年1月1日00:00:00为计时起点,到当前的时间长度
import timeprint(help(time))查看time模块的官方说明time.time() # 返回当前时间的时间戳print(time.time())>>> 1540191340.5649574time.clock() # 计算CPU执行的时间print(time.clock())>>> 3.6655977783544983e-07time.sleep() # 延时多少秒print(time.sleep(3))time.gmtime() # 结构化时间:将时间戳转换成为标准时间utc时区(0时区)print(time.gmtime())>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=22, tm_hour=7, tm_min=4, tm_sec=0, tm_wday=0, tm_yday=295, tm_isdst=0)time.localtime() # 本地时间:将一个时间戳转换为当前时区的时间print(time.localtime())>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=22, tm_hour=15, tm_min=4, tm_sec=26, tm_wday=0, tm_yday=295, tm_isdst=0)time.strftime() # 本地的结构化时间struct_time = time.localtime()print(time.strftime('%Y/%m/%d %X',struct_time))print(time.strftime('%Y/%m/%d %X'))>>>2018/10/22 21:23:45 2018/10/22 21:23:45time.strptime() # 提取想要知道的具体时间:把元组转化为格式化的时间字符串。如果t未指定,将传入time.localtime()print(time.strptime('2018/10/22 09:27:30','%Y/%m/%d %H:%M:%S'))>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=22, tm_hour=9, tm_min=27, tm_sec=30, tm_wday=2, tm_yday=290, tm_isdst=-1)a = time.strptime('2018/10/22 09:27:30','%Y/%m/%d %H:%M:%S')print(a.tm_year)>>> 2018time.ctime() # 把时间戳转换成为时间,格式为固定的print(time.ctime())>>> Mon Oct 22 15:05:04 2018time.mktime() # 把时间转换成为时间戳print(time.mktime(time.localtime()))>>> 1540191919.0
二、datetime模块
import datetimedatetime.datetime.now() # 获取时间print(datetime.datetime.now())>>> 2018-10-22 15:05:37.396534datetime.date.today() # 获取一个日期对象today = datetime.date.today()print(today)>>> 2018-10-22print(today.ctime())>>> Mon Oct 22 00:00:00 2018print(today.timetuple())>>> time.struct_time(tm_year=2018, tm_mon=10, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=295, tm_isdst=-1)print(today.toordinal())>>> 736989print(datetime.date.fromordinal(today.toordinal()))>>> 2018-10-22# 修改日期date = datetime.date(2018,10,22)print(date)date1 = date.replace(year=2018,day=30)print(date1)>>> 2018-10-22 2018-10-30
三、random模块
import random1.random() # 随机生成0-1之间的数字print(random.random())>>> 0.0349573715354106752.randint() # 随机输出范围内的一个整数(包括3)print(random.randint(1,3))>>> 3 or 2 or 13.randrange() # 随机输出范围内的一个整数(不包括3)print(random.randrange(1,3))>>> 1 or 2choice() # 随机输出一个序列中的一个元素print(random.choice(['ALEX','MIKE','JOHN','CAT','DOG']))random.shuffle() #打乱列表的序列,重新排序list = ['ALEX','MIKE','JOHN']random.shuffle(list)print(list)>>> ['JOHN', 'MIKE', 'ALEX']sample() # 以列表形式输出一个序列中的随机几个元素print(random.sample(['ALEX',1,3],1))
Eg.随机生成四位数验证码的两种方法
import random# 方法1:def random_code(): code = '' for i in range(4): if i == random.randint(0,5): add_num = random.randrange(10) else: add_num = chr(random.randrange(65,91)) code += str(add_num) print(code)random_code()# 方法2:def random_code(): code = '' for i in range(4): add = random.choice([random.randrange(10),chr(random.randrange(65,91))]) code += str(add) print(code)random_code()