30 - 时间模块与随机模块(含一阶段测试编程题)

Day 30 时间模块与随机模块(含一阶段测试编程题)

一、'time’模块

import time

1.睡眠:time.sleep

  • 可以在程序需要的地方使用,可以使程序暂停一段时时间

2.获取当前时间:time.time

  • 时间戳:通过时间差来表示具体的时间(指定时间到1970年1月1日0时0分0秒(格林威治时间)之间的时间差,单位是秒)

  • 时间戳保存时间的优点:

    • 节约内存
    • 方便加密
t1 = time.time()
print(t1)   # 1661476346.3788147

3.获取本地时间

  • localtime():获取当前时间(结构体时间)

t2 = time.localtime()
print(t2)

# time.struct_time(tm_year=2022, tm_mon=8, tm_mday=26, tm_hour=9, tm_min=28, tm_sec=1, tm_wday=4, tm_yday=238, tm_isdst=0)

  • 距离时间(距离初始时间想差的时间)

t3 = time.localtime(0)
print(t3)

#time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

t4 = time.localtime(time.time())
print(t4)

# time.struct_time(tm_year=2022, tm_mon=8, tm_mday=27, tm_hour=9, tm_min=21, tm_sec=8, tm_wday=5, tm_yday=239, tm_isdst=0)

4.将结构体时间转换为时间戳: time.mktime

result = time.mktime(t4)
print(result)

# 1661563629.0

5.时间字符串和结构体时间之间的相互转换

  • a.结构体时间转换为字符串 :strftiem(时间格式,结构体时间)

print(f'{t4.tm_year}{t4.tm_mon}{t4.tm_mday}日')
# 2022年8月27日

result = time.strftime('%Y年%m月%d日',t4)
print(result)
# 2022年8月27日

# 星期xx.xx
result = time.strftime('%a %H:%M',t4)
print(result)

# Sat 09:21
  • b.字符串时间转换为结构体时间:time.strptime(字符串时间,时间格式)
result = time.strptime('2021/8/27','%Y/%m/%d')
print(result)

time.struct_time(tm_year=2021, tm_mon=8, tm_mday=27, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=238, tm_isdst=-1)

二、'datetime’模块

from datetime import datetime,timedelta

1.datetime类

  • 01.获取当前时间:datetime.today() 、datetime.now()
t1 = datetime.today()
print(t1,type(t1))
# 2022-08-27 09:29:45.723203 <class 'datetime.datetime'>

t2 = datetime.now()
print(t2,type(t2))
# 2022-08-27 09:29:45.723203 <class 'datetime.datetime'>
  • 02.根据时间值创建时间对象datetime(年,月,日…)
t3 = datetime(2022, 12, 5)
t4 = datetime(2022, 8, 26, 10, 20, 30)
print(t3,t4)

# 2022-12-05 00:00:00 
# 2022-08-26 10:20:30
  • 03.根据时间字符串创建时间对象
t5 = datetime.strptime('2022/8/27','%Y/%m/%d')
print(t5)
# 2022-08-27 00:00:00
  • 04.单独获取具体的时间信息
print(t5.year)      # 2022
print(t5.month)     # 8
print(t5.day)       # 27

print(t5.weekday())  # 5        # 星期值的取值范围:0~6,0表示星期1,此处5代表星期六
  • 05.将时间对象转换成字符串时间
# xxxx年xx月xx日
result = t4.strftime('%Y年%m月%d日')
print(result)       # 2022年08月26日
  • 06.求时间差:时间对象1 - 时间对象2 - 返回时间间隔对象(通过时间间隔对象可以单独获取间隔时间的完整的天数,和秒数)
t1 = datetime(2022, 5, 3, 9, 10)
t2 = datetime(2022, 10, 1, 10, 5)
result = t2 - t1
print(result, type(result))

# # 151 days, 0:55:00 <class 'datetime.timedelta'> 
# 返回时间之间的差值,为时间间隔对象


# 也可单独获取总天数和不满一天的秒数

print(result.days)        # 151
print(result.seconds) 	  # 3300
  • 07.时间对象转换为结构体
result = t1.timetuple()
print(result)
# time.struct_time(tm_year=2022, tm_mon=5, tm_mday=3, tm_hour=9, tm_min=10, tm_sec=0, tm_wday=1, tm_yday=123, tm_isdst=-1)
  • 08.时间对象转换为时间戳
result = t1.timestamp()
print(result)    # 1651540200.0

2.timedelta:时间间隔类

t1 = datetime(2022, 10, 1, 10, 8, 30)
print(t1)          # 2022-10-01 10:08:30

# 10天以后对应的时间
result = t1 + timedelta(days=10)
print(result)       # 2022-10-11 10:08:30

# 32天前对应的时间
result = t1 - timedelta(days=30)
print(result)   	# 2022-09-01 10:08:30

# 30分钟以后
result = t1 + timedelta(minutes=30)
print(result)	    # 2022-10-01 10:38:30

# 5天6小之前
result = t1 - timedelta(days=5, hours=6)
print(result)   	 # 2022-09-26 04:08:30

# 3周以后
result = t1 + timedelta(weeks=3)
print(result)  	     # 2022-10-22 10:08:30


三、随机模块

from random import randint, random, randrange, sample, choice, choices, shuffle

1. 随机小数:random

  • random() - 产生0到1的随机小数
print(random())

# 产生0~20之间的随机小数
# 0*20~1*20  -> 0 ~ 20
print(random()*20)

# 产生5~30之间的随机小数
# 0*25~1*25 -> 0+5 ~ 25+5  ->  5 ~ 30
print(random()*25+5)

# 控制小数的小数位数(四舍五入):round(小数, 需要保留的小数位数)
print(round(3.1415926, 2))      # 3.14

2.随机获取指定等差数列中的一个数字:randrange(起始值,终止值,步长)

print(range(1, 10, 2))      # 1, 3, 5, 7, 9
print(randrange(1, 10, 2))

3.sample(序列, 个数) - 随机获取指定序列中指定个数个元素,产生一个新的列表(无放回抽样)

result = sample([10, 34, 78, 90], 3)
print(result)   # 10,34,90


result = sample('abcd', 1)
print(result)         # c

4.choice(序列) - 随机获取一个元素

result = choice([10, 34, 78, 90])
print(result)   # 78

5.choices(序列,权重,求和权重,数量)

# 有放回抽样
result = choices([10, 34, 78, 90], k=3)
print(result)

# 权重列表中的数字代表对应选项的份数
result = choices(['1000万', '10000', '100', '0'], [1, 2, 100, 200], k=2)
print(result)

6.洗牌 - shuffle(列表)

  • 随机打乱列表元素的顺序
nums = [10, 34, 78, 90]
shuffle(nums)
print(nums)

一阶段测验编程题

1.定义一个函数,可以产生一个指定长度的验证码,(要求是大小写字母或数字的组合)。

from random import randint
# 思路一:可以先完成一个有所有大小写字母和数字的容器,在定义函数,根据指定长度每次随机在容器获取元素。

def create_code(length):
    # 创建验证码对应的所有符号的容器
    all_code = ''


    # 根据大小写字母对应的编码生成所有大小写字母
    small = 97
    big = 65
    for i in rang(26)
        all_code += cha(s) + chr(b)
        small += 1
        big += 1


    # 根据数字对应的编码生成所有数字
    num = 48
    for i in range(10)
        all_code += chr(num)
        num += 1

    # 根据长度获取验证码
    code = ''
	for i in range(lenth):
		code += all_code[randint(0,len(all_code)-1)]
	return code
	
	
# 思路2:创建三个变量,产生随机的大小写字母和数字,在创建容器保存,随机获取其中一个元素

def create_code2(length: int):
	code = ''
	for i in range(lenght)
		c1 = chr(randint(97,26-1))
		c2 = chr(randint(65,26-1))
		c3 = str(randint(0, 9))
		code += [c1, c2, c3][randint(0,2)]
	return code

2.定义一个函数,求指定范围内容所有偶数的和

# 方法1:
def even_sum(start: int, end: int):
    sum1 = 0
    for x in range(start, end+1):
        if x % 2 == 0:
            sum1 += x
    return sum1


# 方法2:
def even_sum2(start: int, end: int):
    if start % 2:
        start += 1
    return sum(range(start, end+1, 2))

3.定一个函数,删除指定列表中的空元素(所有的空值都需要删除)

# 方法1:
def del_null_value(list1: list):
    new_list = []
    for x in list1:
        if x or x == 0:
            new_list.append(x)
    return new_list


# 方法2:
def del_null_value2(list1: list):
    for x in list1[:]:
        if (not x) and (x != 0):
            list1.remove(x)

4.设计⼀个函数,统计字符串中英⽂字⺟和数字各⾃出现的次数。

def num_of_letter_number(str1: str):
    count1 = count2 = 0
    for x in str1:
        if x.isdigit():
            count1 += 1
        elif x.islower() or x.isupper():
            count2 += 1
    return count2, count1

5.设计⼀个函数,计算指定字符串中所有的数字⼦串的和。

# 例如:'abc12你好23mmn1.23'    ->  求 12 + 23 + 1.23 的结果
def sum_num(str1: str):
    from re import findall
    result = findall(r'-?\d+\.?\d*', str1)
    return sum([float(x) for x in result])

6.(1)编写一个矩形类Rect,包含:矩形的宽width;矩形的高height。要求创建对象的时候必须给width和height传值.两个方法:求矩形面积的方法area(),求矩形周长的方法perimeter()

(2)通过继承Rect类编写一个具有确定位置的矩形类PlainRect,其确定位置用矩形的左上角坐标来标识,包含:添加两个属性:矩形左上角坐标start_x和start_y。

要求创建PlainRect对象的时候width和height必须赋值,start_x和start_y可以赋值可以不赋值。
添加一个方法:判断某个点是否在矩形内部的方法is_inside()。如在矩形内,返回True, 否则,返回False。

class Rect:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return self.width*2 + self.height*2


class PlainRect(Rect):
    def __init__(self, width, height, start_x=0, start_y=0):
        super().__init__(width, height)
        self.start_x = start_x
        self.start_y = start_y

    def is_inside(self, p_x, p_y):
        return self.start_x <= p_x <= self.start_x + self.width and self.start_y <= p_y <= self.start_y + self.height

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值