Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Add Date Stamp To Text File

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.

like image 579
The Woo Avatar asked Mar 07 '11 01:03

The Woo


People also ask

How do you insert a date stamp in Python?

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.

How do I display the date in python?

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.


2 Answers

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!')
like image 138
Hugh Bothwell Avatar answered Sep 22 '22 01:09

Hugh Bothwell


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)
like image 31
samplebias Avatar answered Sep 23 '22 01:09

samplebias