[Python杂记001]获取当前时间、日期字符串的代码段,可以用来命名文件
经常因为写入文件时命名发愁,利用时间可以得到一个不会重复的名字作为文件名。
这一代码段返回值就是字符串类型
具体应用就是:
print('{0}.py was saved'.format(strData))
import datetime
def get_datetime_str(style=0):
'''
style=0返回日期_时间字符串
style=1返回日期字符串
style=2返回时间字符串
'''
time_now = datetime.datetime.now()
strData = time_now.strftime('%y%m%d')
strTime = time_now.strftime('%H%M%S')
if style == 1:
return strData
elif style == 2:
return strTime
else:
return strData + '_' + strTime
strData=get_datetime_str(style=1)
print(strData)#220901, 2022年9月1日
strData=get_datetime_str(2)
print(strData)#191018, 19:10:18
strData=get_datetime_str()
print(strData)
print('{0}.py was saved'.format(strData))
'''
220901
191018
220901_191018
220901_191018.py was saved
'''