Python 如何获取datetime字符串作为文件名的后缀?
我需要一个函数来生成带有后缀的数据文件名,后缀必须是当前日期和时间 我想要2014年2月18日15:02这样的日期:Python 如何获取datetime字符串作为文件名的后缀?,python,date,formatting,string-formatting,Python,Date,Formatting,String Formatting,我需要一个函数来生成带有后缀的数据文件名,后缀必须是当前日期和时间 我想要2014年2月18日15:02这样的日期: data_201402181502.txt 但我得到的是:data_2014218152.txt 我的代码 import time prefix_file = 'data' tempus = time.localtime(time.time()) suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm
data_201402181502.txt
但我得到的是:data_2014218152.txt
我的代码
import time
prefix_file = 'data'
tempus = time.localtime(time.time())
suffix = str(tempus.tm_year)+str(tempus.tm_mon)+str(tempus.tm_mday)+
str(tempus.tm_hour)+str(tempus.tm_min)
name_file = prefix_file + '_' + suffix + '.txt'
看起来你想要
date.strftime(format)
格式字符串将允许您控制strftime的输出,请尝试以下操作:
%b-%d-%y
从看起来像你想要的
date.strftime(format)
格式字符串将允许您控制strftime的输出,请尝试以下操作:
%b-%d-%y
从中,您可以使用它来处理前导零的填充,例如在月份:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
如果只需使用str
将整数转换为字符串,它将不会有前导零:str(2)='2'
。但是,您可以使用str.format
语法指定它:“{0:02d}”。您可以使用的格式(2)='02'
,它处理填充前导零,例如在月份:
from time import strftime
name_file = "{0}_{1}.txt".format(prefix_file,
strftime("%Y%m%d%H%M"))
如果只需使用str
将整数转换为字符串,它将不会有前导零:str(2)='2'
。但是,您可以使用str.format
语法:“{0:02d}”。format(2)='02'
与对象一起使用:
与对象一起使用: