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.
1 2 |
import datetime import os |
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:
1 2 |
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") print(timestamp) # Example output: 20210930_124500 |
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:
1 2 3 4 |
filename = "file.txt" filename_without_extension, file_extension = os.path.splitext(filename) new_filename = f"{filename_without_extension}_{timestamp}{file_extension}" print(new_filename) # Example output: file_20210930_124500.txt |
The code above does the following:
- Splits the original filename into two parts – the name without an extension and the extension
- Concatenates the timestamp with the filename without an extension
- 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.
1 2 3 4 5 |
with open(filename, "r") as original_file: content = original_file.read() with open(new_filename, "w") as new_file: new_file.write(content) |
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import datetime import os # Create timestamp timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") # Add timestamp to filename filename = "file.txt" filename_without_extension, file_extension = os.path.splitext(filename) new_filename = f"{filename_without_extension}_{timestamp}{file_extension}" # Save file with new filename with open(filename, "r") as original_file: content = original_file.read() with open(new_filename, "w") as new_file: new_file.write(content) |
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.