python3获取当前时间并格式化生成时间目录

python3获取当前时间,主要用了datetime模块,我们来一起学习下用法吧

代码如下:

#!/usr/local/bin/python3
#coding:utf-8
import datetime
import random
import os

#获取当前时间
nowTime = datetime.datetime.now()
#格式化当前时间,我们只要年月日
now = nowTime.strftime('%Y%m%d')
#打印当前时间
#print(now)
#生成随机数100-999之间
num = random.randint(100, 999)
#将上面的时间和随机数转换为字符串
now,num = str(now),str(num)
#拼接成时间名字的目录
d = now + num
#判断目录是否存在
isExists = os.path.exists(d)
if not isExists:
    os.mkdir(d)
    print('目录创建成功!')
else:
    print('目录已存在!')


内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/530.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。