In Python v2, is there a way to get a date/time stamp and put it into creating a new text file?
IE: When I want to create a new text file and write the contents of my program to it, it will create a new text file with the time/date in it.
Thanks for any help.
We can convert a datetime object into a timestamp using the timestamp() method. If the datetime object is UTC aware, then this method will create a UTC timestamp. If the object is naive, we can assign the UTC value to the tzinfo parameter of the datetime object and then call the timestamp() method.
today() The today() method of date class under DateTime module returns a date object which contains the value of Today's date. Returns: Return the current local date.
import datetime
def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
return datetime.datetime.now().strftime(fmt).format(fname=fname)
with open(timeStamped('myfile.txt'),'w') as outf:
outf.write('data!')
This will prepend a timestamp to the front of the filename:
from datetime import datetime
# define a timestamp format you like
FORMAT = '%Y%m%d%H%M%S'
path = 'foo.txt'
data = 'data to be written to the file\n'
new_path = '%s_%s' % (datetime.now().strftime(FORMAT), path)
open(new_path, 'w').write(data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With