Open In App

How to create filename containing date or time in Python

Last Updated : 18 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Previous Article
Next Article

Similar Reads

Get filename from path without extension using Python
Getting a filename from Python using a path is a complex process. i.e, In Linux or Mac OS, use "/" as separators of the directory while Windows uses "\" for separating the directories inside the path. So to avoid these problems we will use some built-in package in Python. File Structure: Understanding Paths path name root ext /home/User/Desktop/fil
4 min read
fileinput.filename() in Python
With the help of fileinput.filename() method, we can get the last used file name which we have used so far by using fileinput.filename() method. Syntax : fileinput.filename() Return : Return the last used file name. Example #1 : In this example we can see that by using fileinput.filename() method, we are able to get the last used file name by using
1 min read
glob – Filename pattern matching
Glob module searches all path names looking for files matching a specified pattern according to the rules dictated by the Unix shell. Results so obtained are returned in arbitrary order. Some requirements need traversal through a list of files at some location, mostly having a specific pattern. Python’s glob module has several functions that can he
3 min read
Convert Epoch Time to Date Time in Python
Epoch time, also known as Unix time or POSIX time, is a way of representing time as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970. Converting epoch time to a human-readable date and time is a common task in programming, especially in Python. In this article, we will explore some si
3 min read
Python Program to check date in date range
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range. Example: Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), dat
10 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Pandas Series dt.time | Extract Time from Time Stamp in Series
The Series.dt.time attribute returns a NumPy array containing time values of the timestamps in a Pandas series. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime
2 min read
Python - Create nested list containing values as the count of list items
Given a list, the task is to write a Python program to create a nested list where the values are the count of list items. Examples: Input: [1, 2, 3] Output: [[1], [2, 2], [3, 3, 3]] Input: [4, 5] Output: [[1, 1, 1, 1], [2, 2, 2, 2, 2]] Method 1: Using nested list comprehension The list will contain the count of the list items for each element e in
2 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
How to print date starting from the given date for n number of days using Pandas?
In this article, we will print all the dates starting from the given date for n number days. It can be done using the pandas.date_range() function. This function is used to get a fixed frequency DatetimeIndex. Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs) Approac
2 min read
three90RightbarBannerImg