1.time与datetime
时间戳 1970年1月1日之后的秒,即:time.time()
格式化的字符串 2018-10-17 17:11, 即:time.strftime('%Y-%m-%d')
结构化时间 元组包含了:年、日、星期等... time.struct_time 即:time.localtime()
1 time.localtime() 2 time.struct_time(tm_year=2018, tm_mon=10, tm_mday=17, tm_hour=17, tm_min=25, tm_sec=55, tm_wday=2, tm_yday=290, tm_isdst=0) 3 time.gmtime() 4 time.struct_time(tm_year=2018, tm_mon=10, tm_mday=17, tm_hour=9, tm_min=26, tm_sec=10, tm_wday=2, tm_yday=290, tm_isdst=0)
localtime ()不输入获取当前时间,输入秒转换成结构化时间
time.localtime(12457542)
time.struct_time(tm_year=1970, tm_mon=5, tm_mday=25, tm_hour=12, tm_min=25, tm_sec=42, tm_wday=0, tm_yday=145, tm_isdst=0)
x = time.localtime(12457542) print('这是%年的第%s天' % (x.tm_year,x['tm_yday'])) File "<input>", line 1 print('这是%年的第%s天' % (x.tm_year,x['tm_yday'])
gmtime 获取utc标准时间
time.mktime() 传入元组时间,转换为秒数
1 time.mktime(x) 2 12457542.0
time.strftime
1 time.strftime('%Y-%m-%d:%H:%M:%S',x) 2 '1970-05-25:12:25:42'
time.strptime(str,format)
1 time.strptime('1970-05-25:12:25:42','%Y-%m-%d:%H:%M:%S') 2 time.struct_time(tm_year=1970, tm_mon=5, tm_mday=25, tm_hour=12, tm_min=25, tm_sec=42, tm_wday=0, tm_yday=145, tm_isdst=-1)
time.asctime(tuple) ---->string
1 time.asctime() 2 'Wed Oct 17 17:59:53 2018'
time.ctime(seconds) ---->string
1 time.ctime() 2 'Wed Oct 17 18:01:36 2018'
datetime
1 import datetime 2 datetime.datetime.now() #现在的时间 3 datetime.datetime(2018, 10, 17, 18, 7, 38, 622461) 4 datetime.datetime.now() + datetime.timedelta(3) # 三天后的时间 5 datetime.datetime(2018, 10, 20, 18, 8, 56, 949461) 6 datetime.datetime.now() + datetime.timedelta(-3) # 三天前的时间 7 datetime.datetime(2018, 10, 14, 18, 9, 59, 176062) 8 datetime.datetime.now() + datetime.timedelta(hours = 3) 9 datetime.datetime(2018, 10, 17, 21, 10, 11, 130462) # 三个小时后 10 datetime.datetime.now() + datetime.timedelta(hours = -3) 3三个小时前 11 datetime.datetime(2018, 10, 17, 15, 10, 22, 774462)
二:random模块(随机)
1.random.random 随机0-1的值
import random random.random() 0.48301924118006734 random.random() 0.39893309639174046
random.uniform(5,6) 5.239822390830757 random.uniform(5,6) 5.360649805130647
uniform 可以指定区间
2. random.randint(1,5) 随机【1-5】 范围类的整数包括1,5
random.randint(1,5) 2 random.randint(1,5) 3
3.random.randrange(1,6) 1-6 不包含6
random.randrange(1,6) 2 random.randrange(1,6) 3 random.randrange(1,6) 3
4.random.choice() 传入序列,字符串,列表,元组
random.choice('hello,WOlrd') 'd' random.choice('hello,WOlrd') 'l'
4.random.sample('qweerttyyyu',2) 从前面的序列中随机取两位
random.sample('qweerttyyyu',2) ['t', 'e'] random.sample('qweerttyyyu',2) ['y', 'r']
5.random.shuffle(a) 打乱a的顺序
a = [i for i in range(10)] a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] random.shuffle(a) a [3, 0, 7, 4, 9, 8, 2, 6, 1, 5]
可以用作生成随机验证码
import random checkcode = '' for i in range(4): current = random.randrange(0,10) if current <= i: checkcode += str(current) else: current += 65 + random.randint(0,26) if current >= 65 and current <=90: checkcode += chr(current) else: checkcode += chr(current + 6) print(checkcode)
时间紧迫,字母出现的可能性更高