You can create a file name with the current date and time in Python using the datetime module by following these steps.
Step 1: Get the Current Date and Time
To get the current date time, use the datetime.now() or datetime.today() methods in the datetime package. Those methods return a datetime object that represents the current date and time.
Here is an example:
1 2 3 4 |
from datetime import datetime now = datetime.now() # datetime.today() print(now) |
Output:
2023-03-31 20:44:16.703033
You can also extract time and date separately using date() and time() functions as follows
1 2 3 4 5 6 |
from datetime import datetime now_date = datetime.now().date() print(now_date) now_time = datetime.now().time() print(now_time) |
Output:
2023-03-31 20:48:56.603331
Step 2: Format datetime Output in Step 1
The datetime object can be formatted explicitly using datetime.strftime(<format>) method. This method takes the datetime, date, or time object and returns a string representation of the object based on the <format> provided.
Here are a few examples of formate codes supported by strftime():
Formatting code | Description | Example |
%d | Two-digit day of the month. | 01, 02, …, 31 |
%m | Two-digit representation of the month | 01, 02, …, 12 |
%y | Two-digit representation of the year | 00, 01, 99 |
%Y | Four-digit representation of the year | 0000, 0001, …., 9999 |
%H | Two-digit 24-hour clock | 00, 01, …, 23 |
%I | Two-digit 12-hour clock | 01, 02, …, 12 |
%M | Two-digit minute number | 00, 01, …, 59 |
%S | Two-digit second number | 00, 01, …, 59 |
You can find more formatting codes from the strftime() documentation.
We can use the formatting codes above as shown in the following examples
1 2 3 4 |
from datetime import datetime now1 = datetime.now().strftime("%Y%m%d_%H%M%S") print(now1) |
Output:
20230331_210701
1 2 3 4 5 |
from datetime import datetime #Hour in the 12-hour clock system now2 = datetime.now().strftime("%d%m%Y_%I%M") print(now2) |
Output:
31032023_0907
Step 3: Create a File/ Folder or Rename an Existing One by Adding Current Datetime
This step discusses creating a file or folder with the current datetime in their name or renaming an existing file/ folder.
Creating a new file/ folder with current datetime
We can now create a file (in this case, a txt file) using with context manager and open() function as shown below.
1 2 3 4 5 6 7 8 |
from datetime import datetime now3 = datetime.now().strftime("%Y%m%d_%H%M%S") # Create the file name with the current date. filename = f"file_{now3}.txt" # for Python 3.6+ or "file_{}.txt".format(now3) for Python before v3.6 # Open the text file in append (a) mode with open(filename, "a") as f: f.write("This is a test string") |
That creates a txt file with the current date time, for example, file_20230331_212104.txt.
Note: The code above may create a new file at every execution as time passes. You may want to rename files if that is not what you expect.
A new folder can be created using the os module with the os.makedirs(<folder_name>) function.
Rename a file or folder to include current datetime
To rename a file/ folder, we can use the os.rename() function, as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import os from datetime import datetime old_name = "/home/kiprono/Desktop/file_permission1.py" # Create the current datetime object in a given format now5 = datetime.now().strftime("%Y%m%d%H%M") # extract the filename and the extension from the old_name path filename, extension = os.path.splitext(old_name) print(filename, extension) # new name is the filename concatenated with the current datetime and the extension new_name = filename + now5 + extension print(new_name) # rename the file into the new name with current datetime os.rename(old_name, new_name) |
Rename all files and subfolders in a given directory recursively
You can use os.walk() to traverse all the files and subfolders in a directory tree. Here’s an example implementation that uses os.walk:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import os from datetime import datetime def rename_files(path): for dirpath, dirnames, filenames in os.walk(path): # Rename all files in the directory and subdirectories. for filename in filenames: current_name, extension = os.path.splitext(filename) now6 = datetime.today().strftime("%Y%m%d%H%M") new_name = f"{current_name}_{now6}{extension}" os.rename(os.path.join(dirpath, filename), os.path.join(dirpath, new_name)) # Rename subdirectories in the current directory for dirname in dirnames: now7 = datetime.now().strftime("%Y%m%d_%H%M") new_name = f"{dirname}_{now7}" os.rename(os.path.join(dirpath, dirname), os.path.join(dirpath, new_name)) rename_files(os.path.join(dirpath, new_name)) # Call the function with the path to your directory rename_files("./folder1") |
Conclusion
This guide discussed using Python’s datetime module to create a filename with the current date and time. By using the datetime.now() or datetime.today() method, we can get the current date and time and then format it using the strftime() to create a string representation of the datetime object.
We can then use this string representation to create a new file or rename an existing file by adding the current datetime to the file’s name. However, caution should be taken when using the current datetime on filenames to avoid overriding existing files or creating unnecessary duplicates.