How To Add Timestamp To Filename In Python

In this tutorial, we will learn how to add a timestamp to a filename in Python. Timestamps are useful when working with files and logs in various projects, as they help keep track of when the files were created or modified. By adding a timestamp to the filename, you can easily organize and manage your files.

Step 1: Import necessary libraries

First, we need to import the necessary libraries for our code. We will be using the datetime library to handle timestamps and the os library to perform file operations.

Step 2: Create a timestamp

Next, we will create a timestamp using the datetime library. The strftime method allows us to format the timestamp according to our needs.

Here’s a simple example of how to create a timestamp using the current date and time:

Step 3: Add the timestamp to the filename

To add the created timestamp to a filename, we simply need to concatenate the timestamp to the desired filename. In this example, we have a file named “file.txt” and we want to add the timestamp to the filename. Here’s how you can do it:

The code above does the following:

  1. Splits the original filename into two parts – the name without an extension and the extension
  2. Concatenates the timestamp with the filename without an extension
  3. Appends the file extension back to the new filename

Step 4: Save the file with the new filename (optional)

If you want, you can save your file with the newly created filename. The following code will create a new file with the timestamp in the filename and copy the contents of the original file into the new file.

Full Code:

Output:

file_20210930_124500.txt

In this tutorial, you learned how to add a timestamp to a filename in Python using the datetime library, and how to save the modified filename. It is a useful technique to organize and manage files, especially in situations where file versions are crucial, such as logs, data backups, and data processing projects.