Trimax
Trimax

Reputation: 2473

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'

Upvotes: 0

Views: 259

Answers (3)

falsetru
falsetru

Reputation: 368944

Using str.format with datetime.datetime object:

>>> import datetime
>>> '{}_{:%Y%m%d%H%M}.txt'.format('filename', datetime.datetime.now())
'filename_201402182313.txt'

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121975

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'.

Upvotes: 3

Joan Smith
Joan Smith

Reputation: 931

Looks like you want

 date.strftime(format)

The format string will allow you to control the output of strftime, try something like: "%b-%d-%y" From http://docs.python.org/2/library/datetime.html

Upvotes: 1

Related Questions