python标准库

os模块

os模块主要是对文件,目录的操作

常用的方法有:

os.mkdir()  创建目录

# os.mkdir(dirname)
# 创建目录
# os.mkdir("testdir")

os.listdir()  列出目录的文件名称,相当于ls命令

print(os.listdir("./"))

os.removedirs()  删除目录文件

# 删除目录
os.removedirs("testdir")

os.getcwd()  获取当前目录

# 获取当前路径
print(os.getcwd())

os.path.exists(dir or file) 判断文件或者目录是否存在

# 判断目录或者文件是否存在
if not os.path.exists("test"):
    os.mkdir("test")
print(os.getcwd())
if not os.path.exists("test/test.txt"):
    # f = open("test/test.txt", "w")
    # f.write("test os lib")
    # f.close()
    with open("test/test.txt", "w") as f:
        f.write("test os lib")
os.remove("test/test.txt")
os.removedirs("test")

time模块

# time模块获取当前时间及时间格式的模块

time.asctime()

  返回Sun May 16 16:40:28 2021这种西方格式的当前时间

print(time.asctime())

 

time.time()

返回从1970-1-1 00:00:00开始的秒计数值,即时间戳
print(time.time())

比如:1621154535.6239324

time.localtime()

格式化时间戳为本地的时间。 如果sec参数未输入,则以当前时间为转换标准。

print(time.localtime())

比如:time.struct_time(tm_year=2021, tm_mon=5, tm_mday=16, tm_hour=16, tm_min=44, tm_sec=55, tm_wday=6, tm_yday=136, tm_isdst=0)

time.strftime()

函数接收以时间元组,并返回以可读字符串表示的当地时间,格式由参数 format 决定。

print(time.strftime("%Y-%m-%d %H:%M:%S %A"))

比如:2021-05-16 16:51:59 Sunday

https://www.runoob.com/python/att-time-strftime.html

例子:

# 获取两天前的时间
# 首先获取当前时间的时间戳
now_time = time.time()
print(time.strftime("%Y-%m-%d %H:%M:%S %A"))
# 通过当前时间戳计算出2天前的时间戳
two_day_before = now_time - 60*60*24*2
# 将时间戳转换为struct_time格式的元组
time_tuple = time.localtime(two_day_before)
# 将转换后的时间通过strftime函数展示出来
print(time.strftime("%Y-%m-%d %H:%M:%S %A", time_tuple))

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值