Open In App
Related Articles

How to create filename containing date or time in Python

Improve Article
Improve
Save Article
Save
Like Article
Like

Prerequisite: DateTime module

In this article, we are going to see how to create filenames with dates or times using Python

For this, we will use the DateTime module. First, import the module and then get the current time with datetime.now() object. Now convert it into a string and then create a file with the file object like a regular file is created using file handling concepts in Python.

Example 1: Creating text file containing date/time 

Python3




# import module
from datetime import datetime
 
# get current date and time
current_datetime = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
print("Current date & time : ", current_datetime)
 
# convert datetime obj to string
str_current_datetime = str(current_datetime)
 
# create a file object along with extension
file_name = str_current_datetime+".txt"
file = open(file_name, 'w')
 
print("File created : ", file.name)
file.close()


Output:

Current date & time :  2023-05-11 07-21-36
File created :  2023-05-11 07-21-36.txt

Any type of file can be created in this manner if the required extension is provided correctly.

Example 2:  Creating CSV file containing date/time 

Python3




# import module
from datetime import datetime
 
# get current date and time
current_datetime = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
print("Current date & time : ", current_datetime)
 
# convert datetime obj to string
str_current_datetime = str(current_datetime)
 
# create a file object along with extension
file_name = str_current_datetime+".csv"
file = open(file_name, 'w')
 
print("File created : ", file.name)
file.close()


Output:

Current date & time :  2023-05-11 07-22-34
File created :  2023-05-11 07-22-34.csv

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 18 May, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials