When working with files in Python, sometimes you need to name them using the current date and time. This makes us easier to organize files, avoid overwriting existing ones, and keep track of when each file was created. Python has built-in tools like “datetime” and “os” that make this simple to do.
In this tutorial, you will learn how to use these tools to create file names that include the date and time. This is a useful skill for tasks like making backups, saving logs, or managing files in an automated way. Let’s get started!
Setting Up Your Environment
Before working on programming, ensure that you have Python installed on your system. All the systems must have Python compiler installed to run applications. You can download it from the official Python website and install on your system freely. This tutorial will use Python 3, so make sure you have a version of Python 3.x installed.
Utilizing the datetime Module
The datetime module in Python is used for generating date and time based strings that can be used in naming files and folders. Here’s a simple example of how to use the datetime module to get the current date and time formatted as a string:
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Format the date and time as a string
date_time_str = now.strftime("%Y-%m-%d_%H-%M-%S")
print(date_time_str)
This code snippet will print the current date and time in the format YYYY-MM-DD_HH-MM-SS, which is a common format for naming files and folders because it sorts chronologically when viewed in most file systems.
Create Date and Time-Based File Names
With the date and time string ready, you can now proceed to create files and folders using Python’s os module. Here’s how you can create a folder named with the current date and time:
import os
# Create a directory named after the current date and time
os.makedirs(date_time_str)
Similarly, you can create a file with a date and time-based name. If you want to create a text file, for example, you could append the .txt extension to the date_time_str variable:
# Create a text file with the current date and time as its name
file_name = f"{date_time_str}.txt"
with open(file_name, 'w') as file:
file.write("This is an example of creating a file with a date and time-based name.")
Craft a Complete Script to Create File and Folder
Let’s Craft a complete script that will create a directory with using current date. Also create a text file with current date and time in their name. This can be helpful for creating directory for daily backups and generate log files in a organized way.
The script is:
import os
from datetime import datetime
# Get the current date and time
now = datetime.now()
# Create a directory named after the current date and time
custom_dirname = now.strftime("%Y-%m-%d")
dir_name = f"Backup_{custom_dirname}"
os.makedirs(dir_name)
# Create a text file with the current date and time as its name
custom_filename = now.strftime("%Y-%m-%d_%H-%M-%S")
file_name = f"Log_{custom_filename}.txt"
with open(file_name, 'w') as file:
file.write("This is an sample log file with a date and time-based name.")
Save the above script in a file named “script.py” and execute it.
You will see a directory and a file created in current directory with date & time in there names.
Conclusion
In this tutorial you have learned about creating date and time-based file names in Python using built-in tools like “datetime” and “os”. These tools helps you to make scripts that name files and folders with the current date and time automatically. This is useful for keeping files and folders organized, making backups, or creating logs. Using these tools, you can easily add dates and times to your file names in your scripts.