常用模块——时间模块、随机数模块

时间模块

和时间有关系的我们就要用到时间模块。在使用模块之前,应该首先导入这个模块。

#常用方法
1.time.sleep(secs)
(线程)推迟指定的时间运行。单位为秒。
2.time.time()
获取当前时间戳

表示时间的三种方式

在Python中,通常有这三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串:

(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。

(2)结构化时间(struct_time): 不是让程序员看的,是让计算机看的
元组(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天等)

索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2011
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 60
6 tm_wday(weekday) 0 - 6(0表示周一)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为0

(3)格式化的时间字符串(Format String): ‘1999-12-06’

python中时间日期格式化符号

%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

具体使用

#导入时间模块
import time

#时间戳
time.time()
# > 1500875844.800804

# 结构化时间(struct_time)
res = time.localtime()
print(res)
# > time.struct_time(tm_year=2023, tm_mon=3, tm_mday=9, tm_hour=17, tm_min=8, tm_sec=33, tm_wday=3, tm_yday=68, tm_isdst=0)
print(res.tm_year)  # 2023
print(res.tm_mon)  # 3
print(res.tm_hour)  # 17
print(res[0])  # 2023
print(res[1])  # 3
print(res[2])  # 9
print(res[3])  # 17
print(res[4])  # 9

# 格式化时间(format string)
# res = time.strftime('%Y-%m-%d')  # 返回当前时间格式化之后的结果
res = time.strftime('%Y-%m-%d %H:%M:%S')  
res1 = time.strftime('%y-%m-%d %X') 
res2 = time.strftime('%Y-%m-%d %h:%M')  
res3 = time.strftime('%Y-%m-%d %H')  
print(res)  # 2023-03-09 17:03:59
print(res1)  # 23-03-09 17:03:59
print(res2)  # 2023-03-09 Mar:03
print(res3)  # 2023-03-09 17

小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的

几种格式之间的转换

时间戳-->结构化时间

#time.gmtime(时间戳)    #UTC时间,与英国伦敦当地时间一致
#time.localtime(时间戳) #当地时间。例如我们现在在北京执行这个方法:与UTC时间相差8小时,UTC时间+8小时 = 北京时间 
>>>time.gmtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

>>>time.localtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)

#结构化时间-->时间戳 
#time.mktime(结构化时间)
>>>time_tuple = time.localtime(1500000000)
>>>time.mktime(time_tuple)
1500000000.0

结构化时间-->字符串时间

#time.strftime("格式定义","结构化时间")  结构化时间参数若不传,则显示当前时间
>>>time.strftime("%Y-%m-%d %X")
'2017-07-24 14:55:36'
>>>time.strftime("%Y-%m-%d",time.localtime(1500000000))
'2017-07-14'

#字符串时间-->结构化时间
#time.strptime(时间字符串,字符串对应格式)
>>>time.strptime("2017-03-16","%Y-%m-%d")
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1)
>>>time.strptime("07/24/2017","%m/%d/%Y")
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)

结构化时间 --> %a %b %d %H:%M:%S %Y串

#time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
>>>time.asctime(time.localtime(1500000000))
'Fri Jul 14 10:40:00 2017'
>>>time.asctime()
'Mon Jul 24 15:18:33 2017'

#时间戳 --> %a %b %d %H:%M:%S %Y串
#time.ctime(时间戳)  如果不传参数,直接返回当前时间的格式化串
>>>time.ctime()
'Mon Jul 24 15:19:07 2017'
>>>time.ctime(1500000000)
'Fri Jul 14 10:40:00 2017' 

import time
true_time=time.mktime(time.strptime('2017-09-11 08:30:00','%Y-%m-%d %H:%M:%S'))
time_now=time.mktime(time.strptime('2017-09-12 11:00:00','%Y-%m-%d %H:%M:%S'))
dif_time=time_now-true_time
struct_time=time.gmtime(dif_time)
print('过去了%d年%d月%d天%d小时%d分钟%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1,
                                       struct_time.tm_mday-1,struct_time.tm_hour,
                                       struct_time.tm_min,struct_time.tm_sec))

datetime模块

时间

import datetime

# 自定义日期
res = datetime.date(2019, 7, 15)
print(res)  # 2019-07-15

# 获取本地时间
# 年月日
now_date = datetime.date.today()
print(now_date)  # 2019-07-01
# 年月日时分秒
now_time = datetime.datetime.today()
print(now_time)  # 2019-07-01 17:46:08.214170
"""datetime:年月日 时分秒   date:年月日   time:时分秒"""


# 无论是年月日,还是年月日时分秒对象都可以调用以下方法获取针对性的数据
# 以datetime对象举例
print(now_time.year)  # 获取年份2019
print(now_time.month)  # 获取月份7
print(now_time.day)  # 获取日1
print(now_time.weekday())  # 获取星期(weekday星期是0-6) 0表示周一
print(now_time.isoweekday())  # 获取星期(weekday星期是1-7) 1表示周一
'''year,month,day, 是通过属性调用
weekday()是通过方法调用的'''

timedelta对象

# timedelta对象 重点
# 可以对时间进行运算操作
"""
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象

"""
1.日期对象 = 日期对象 +/- timedelta对象
求3天后的时间
current_time = datetime.datetime.now()
print(current_time)  # 2023-03-09 17:16:33.323737
t_time = datetime.timedelta(days=3)
print(current_time + t_time)  # 2023-03-12 17:16:33.323737

求10天,11时50分后的时间
t_time2 = datetime.timedelta(days=10, hours=11, minutes=50)
print(current_time + t_time2)  # 2023-03-20 05:08:25.374756

求3周前的时间
t_time3 = datetime.timedelta(weeks=3)
print(current_time - t_time3)  # 2023-02-16 17:18:56.918351


2.timedelta对象 = 日期对象 +/- 日期对象
current_time = datetime.datetime.now()
print(current_time)  # 2023-03-09 17:16:33.323737
t_time = datetime.timedelta(days=3)
current_time2 = current_time + t_time  # 2023-03-12 17:16:33.323737
time2 = current_time2 - current_time
print(time2)  # 3 days, 0:00:00

'''格式不同的话,不能加减,会报错'''
today = datetime.date.today()
print(today)  # 2023-03-09
print(today - datetime.date(2019, 12, 21))  # 1174 days, 0:00:00
# 练习2
import datetime

# 获得本地日期 年月日
tday = datetime.date.today()
# 定义操作时间 day=7 也就是可以对另一个时间对象加7天或者减少7点
tdelta = datetime.timedelta(days=7)

# 打印今天的日期
print('今天的日期:{}'.format(tday))  # 2019-07-01
# 打印七天后的日期
print('从今天向后推7天:{}'.format(tday + tdelta))  # 2019-07-08
# 总结:日期对象与timedelta之间的关系
"""
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象

验证:

"""
# 定义日期对象
now_date1 = datetime.date.today()
# 定义timedelta对象
lta = datetime.timedelta(days=6)
now_date2 = now_date1 + lta  # 日期对象 = 日期对象 +/- timedelta对象
print(type(now_date2))  # <class 'datetime.date'>
lta2 = now_date1 - now_date2  # timedelta对象 = 日期对象 +/- 日期对象
print(type(lta2))  # <class 'datetime.timedelta'>


# 小练习 计算举例今年过生日还有多少天
birthday = datetime.date(2019, 12, 21)
now_date = datetime.date.today()
days = birthday - now_date
print('生日:{}'.format(birthday))
print('今天的日期:{}'.format(tday))
print('距离生日还有{}天'.format(days))


# 总结年月日时分秒及时区问题
import datetime

dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()  # UTC时间与我们的北京时间cha ju

print(dt_today)
print(dt_now)
print(dt_utcnow)

random模块

import random

print(random.random())  # 产生大于0且小于1之间的小数
# > 结果是:0.8906635817589553
print(random.uniform(1, 5))  # 返回1-5之间的小数,不包括两头
# > 结果是:1.0409774675849537


#随机整数
print(random.randint(1, 10))  # 返回1-10的整数,包括两头的
print(random.randrange(1, 10, 2))  # 大于等于1且小于10之间的奇数
print(random.randrange(1, 10, 3))  # 大于等于1且小于10之间的1,4,7,步长为3


#随机选择一个返回
print(random.choice(['一等奖', '2等奖', '3等奖', '4等奖', '5等奖', '谢谢惠顾', '再来一瓶']))
#随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample(['一等奖', '2等奖', '3等奖', '4等奖', '5等奖', '谢谢惠顾', '再来一瓶'],3))
# > 结果是:['5等奖', '3等奖', '谢谢惠顾']


#打乱列表顺序
l = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A']
random.shuffle(l)  # 打乱顺序
print(l)
# > 结果是:[8, 'K', 5, 9, 2, 4, 'J', 10, 'A', 6, 3, 7, 'Q']

练习1: 生成随机验证码

'''生成随机4位,5位,6位的验证码'''

import random

# 随机验证码里面的字符,是数字,字母组成三种情况任意一种的组合
def get_code(n):
    code = ''  # 存储生成的随机验证码
    # 6位的验证码
    for i in range(n):
        # 1. 产生0-9之间的任意一个数据
        random_int = str(random.randint(0, 9))
        # 2. 产生大写字母
        random_upper = chr(random.randint(65, 90))  # A-Z
        # 3. 产生小写字母
        random_lower = chr(random.randint(97, 122))  # a-z
        # 4. 要从以上三种情况中随机选出一个字符来
        temp = random.choice([random_int, random_lower, random_upper])
        # print(temp,end='')
        # code = ''.join([code, temp])
        code += temp
    return code
print(get_code(6))  # iG53H4
res = get_code(4)
print(res)  # oR2W

练习2: 生成订单号


import time
 
 
#  生成订单号
def get_order_code():
    #  年月日时分秒+time.time()的后7位
    order_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) + str(time.time()).replace('.', '')[-7:])
    return order_no

print(get_order_code()) 

'''
年月日时分秒+time.time()的后7位
格式化时间:time.strftime
结构化时间:time.localtime()类元组形式
print(time.time())  # 1678514912.9067729  # 浮点型,所以要先转化为字符串再索引取值
函数replace(self, old, new, count=None) 用新字符串替换旧字符串,第三个参数是替换的个数
print(get_order_code())  # 202303111408329067729
'''
posted @ 2023-03-13 20:18  星空看海  阅读(42)  评论(0编辑  收藏  举报