Search code examples
pythondateformattingstring-formatting

How get a datetime string to suffix my filenames?


I need a function to generate datafile names with a suffix which must be the current date and time.

I want for the date Feb, 18 2014 15:02 something like this:

data_201402181502.txt

But this is that I get: data_2014218152.txt

My code...

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'

Solution

  • You can use time.strftime for this, which handles padding leading zeros e.g. on the month:

    from time import strftime
    
    name_file = "{0}_{1}.txt".format(prefix_file, 
                                     strftime("%Y%m%d%H%M"))
    

    If you simply turn an integer to a string using str, it will not have the leading zero: str(2) == '2'. You can, however, specify this using the str.format syntax: "{0:02d}".format(2) == '02'.