dev_fight
dev_fight

Reputation: 3515

How to add the date to the file name?

from datetime import datetime, date, time

now = datetime.now()
print now #2013-05-23 04:07:40.951726    
tar = tarfile.open("test.tar", "w")

How to add the date to the file name? For example: test2013_05_23_04_07.tar

Upvotes: 4

Views: 12830

Answers (3)

Robert Lujo
Robert Lujo

Reputation: 16371

I usually use something like this:

tst = datetime.datetime.now().isoformat("-").split(".")[0].replace(":","-")
tar = tarfile.open("test%s.tar" % now, "w")

produces filename test2013-05-23-14-37-51.tar.

Upvotes: 4

pedram
pedram

Reputation: 3087

I have a function I use fairly often:

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S-{fname}'):
        import datetime
        # This creates a timestamped filename so we don't overwrite our good work
        return datetime.datetime.now().strftime(fmt).format(fname=fname)

invoke with

fname = timeStamped('myfile.xls')

Result: 2013-05-23-08-20-43-myfile.xls

Or change the fmt:

fname2 = timeStamped('myfile.xls', '%Y%m%d-{fname}')

Result: 20130523-myfile.xls

Upvotes: 4

Inbar Rose
Inbar Rose

Reputation: 43447

With string formatting.

from datetime import datetime, date, time

now = datetime.now()
print now #2013-05-23 04:07:40.951726    
tar = tarfile.open("test%s.tar" % now, "w")

Or using .format() in Python 3.+

tar = tarfile.open("test{}.tar".format(now), "w")

Note, you can also decide how you want datetime.now() to be displayed using .strftime():

print now.strftime('%Y-%m-%d')
>>> 2013-05-23

Upvotes: 6

Related Questions