Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to create filename containing date or time in Python

  • Last Updated : 31 Aug, 2021

Prerequisite: DateTime module

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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()
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 : 2021-08-19 13:17:48.408908

File created :  2021-08-19 13:17:48.408908.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()
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 :  2021-08-19 13:19:29.667423

File created :  2021-08-19 13:19:29.667423.csv




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!