python自动化常用模块_Python自动化开发 - 常用模块(一)

本节内容

一、模块介绍

模块,是一堆代码实现了某个功能的代码集合。

类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合

而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块

如:os 是系统相关的模块;file是文件操作相关的模块

模块分为三种:

自定义模块

内置标准模块(又称标准库)

开源模块

二、time&datetime模块

import time

import datetime

print(time.time()) # 通用OS诞生元年至今时间戳

t = time.localtime() # 返回本地时间的struct time对象格式

print(t) # 可用于定制化输出

print("%s-%s-%s %s:%s:%s" % (t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec))

print(time.gmtime()) # 返回utc时间的struc时间对象格式

# 日期字符串转成时间戳

string_2_struct = time.strptime("2017/02/20", "%Y/%m/%d") # 将日期字符串转成struct时间对象格式

print(string_2_struct)

struct_2_stamp = time.mktime(string_2_struct) # 将struct时间对象转成时间戳

print(struct_2_stamp)

# 将时间戳转为字符串格式

print(time.gmtime(time.time()-86640)) # 将utc时间戳转换成struct_time格式

print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())) # 将utc struct_time格式转成指定的字符串格式

# 时间加减

print(datetime.datetime.now()) # 返回系统当前时刻 2017-02-18 15:59:33.948776

print(time.time()) # 时间戳

print(datetime.date.fromtimestamp(time.time())) # 时间戳直接转成日期格式 2017-02-18

print(datetime.datetime.now())

print(datetime.datetime.now() + datetime.timedelta(hours=1, minutes=10)) # 当前时间加1小时,10分钟

print(datetime.datetime.now().replace(year=2016)) # 时间替换为2016年

时间戳与时间字符串相互转化如下:

84c4c0963ca1d60e796d87fa75de1a1d.png

三、random模块

import random

import string

print(random.randint(1, 10)) # 随机1-10,包括10的任意整数

print(random.randrange(1, 20, 2)) # 随机1-20,步长为2,但不包括20,随机整数

print(random.sample(range(100), 2)) # 从源列表中任意取2的元素,组成列表

# 生成4位验证码

source = string.ascii_uppercase + string.digit

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值