2014-02-18 9 views
0

我需要一个函数来生成带有后缀的数据文件名称,它必须是当前的日期和时间。如何让日期时间字符串后缀我的文件名?

我想要的日期Feb,18 2014 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_mday)+ 
    str(tempus.tm_hour)+str(tempus.tm_min) 
name_file = prefix_file + '_' + suffix + '.txt' 

回答

3

您可以使用time.strftime这一点,它处理填充前导零例如上月:

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'

+0

感谢@jonsharpe – Trimax

相关问题