Open In App

How to get file creation and modification date or time in Python?

Last Updated : 15 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We often need to access various file properties for different purposes. Among the file properties, the creation and modification time of a file are the most commonly used ones. We can achieve the same functionality and use it for various utility purposes, using multiple methods. 

You can use functions from the time module and datetime module to get the file creation and modification of date or time.

Using the OS and Time module

We will use the getctime() and getmtime() function, found inside the path module in the os library, for getting the creation and modification times of the file. 

  • getctime()- returns the creation time.
  • getmtime()-returns the last modification time.

Both the above functions return time in seconds since EPOCH (00:00:00 UTC on 1 January 1970). Since that number doesn’t resemble an understandable timestamp, we would have to convert that time so that it becomes recognizable. For that purpose, we would be using the ctime() function found inside the time library.

Example 1: Getting creation and modification time using getctime() and getmtime() methods.

The timestamp of the above code has the following format qualifiers –

[Day](3) [Month](3) [day](2) [Hours:Minutes:Seconds](8) [Year](4)

Python3
import os
import time

# Path to the file/directory
path = "myfile.txt"

# Both the variables would contain time
# elapsed since EPOCH in float
ti_c = os.path.getctime(path)
ti_m = os.path.getmtime(path)

# Converting the time in seconds to a timestamp
c_ti = time.ctime(ti_c)
m_ti = time.ctime(ti_m)

print(f"The file located at the path {path} \
was created at {c_ti} and was "
      f"last modified at {m_ti}")

Output:

The file located at the path myfile.txt was created at Mon Jun 27 14:16:30 2022 and 
was last modified at Thu Jul 7 16:25:52 2022

Where the word inside the bracket is the cue for what is being displayed, and the number following it within the parenthesis displays the length it will occupy.

Example 2: Get creation and modification time in ISO 8601 format

By default, the ctime() function would return a timestamp of the aforementioned syntax. In order to change it, we would have to pass it to strptime() function (also found inside the time library) to create a time structure (object) out of it. Then we can pass format specifiers to strftime(), to create a custom timestamp out of the time structure. In the following code, we will be getting the modification time of the same file in ISO 8601 timestamp format. 

Python3
import os
import time

path = r"myfile.txt"

ti_m = os.path.getmtime(path)

m_ti = time.ctime(ti_m)

# Using the timestamp string to create a 
# time object/structure
t_obj = time.strptime(m_ti)

# Transforming the time object to a timestamp 
# of ISO 8601 format
T_stamp = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)

print(f"The file located at the path {path} was last modified at {T_stamp}")

Output:

The file located at the path myfile.txt was last modified at 2022-07-07 16:25:52

Using the Datetime Module

Classes for working with date and time are provided by the Python datetime module. Numerous capabilities to deal with dates, times, and time intervals are provided by these classes. Python treats date and datetime as objects, so when you work with them, you’re working with objects rather than strings or timestamps.

Example 1: Convert creation and modification time into a Datetime object

We can convert the time returned by the getctime() method and the getmtime() method into a DateTime object using the datetime.datetime.fromtimestamp() method.

Python3
import datetime
import os

path = r"myfile.txt"

# file modification 
timestamp = os.path.getmtime(path)

# convert timestamp into DateTime object
datestamp = datetime.datetime.fromtimestamp(timestamp)
print('Modified Date/Time:', datestamp)

# file creation 
c_timestamp = os.path.getctime(path)

# convert creation timestamp into DateTime object
c_datestamp = datetime.datetime.fromtimestamp(c_timestamp)

print('Created Date/Time on:', c_datestamp)

Output:

Modified Date/Time: 2022-07-07 16:25:52.490759
Created Date/Time on: 2022-06-27 14:16:30.123721

Example 2: Get Creation And Modification Time Of a File Using pathlib.path

pathlib module in Python allows you to work with file paths and file systems. pathlib.path is a submodule of pathlib library that allows you to work with file paths in an object-oriented manner.

We will use the stat().st_mtime function to get the modification time of the file and stat().st_ctime to get the creation time of the file.

Python3
import datetime
import pathlib

# create a file path
path = pathlib.Path(r'myfile.txt')

# get modification time
timestamp = path.stat().st_mtime

# convert time to dd-mm-yyyy hh:mm:ss
m_time = datetime.datetime.fromtimestamp(timestamp)
print('Modified Date/Time:', m_time)

# get creation time on windows
current_timestamp = path.stat().st_ctime
c_time = datetime.datetime.fromtimestamp(current_timestamp)
print('Created Date/Time on:', c_time)

Output:

Modified Date/Time: 2022-07-07 16:25:52.490759
Created Date/Time on: 2022-06-27 14:16:30.123721

We have used the OS module and pathlib module to get the creation and modification time of the file. We have also used the datetime module and time module to convert the returned time into a more understandable format. Getting modification and creation time of the file is an important operation of file handling.



Previous Article
Next Article

Similar Reads

Python - Move Files To Creation and Modification Date Named Directories
We all understand how crucial it is to manage files based on their creation and modification dates. So, in this article, we will try to build a Python script that would move all of your files to new directories based on their creation and modification dates. Basically, it will look for directories and, if any are found, it will extract all the file
4 min read
Get sorted file names from a directory by creation date in Python
In this article, we will understand how to retrieve sorted file names from a directory using Python. For this, we would make use of the Python glob library's glob function. There is no need to install this module externally because it is already included with Python. Firstly, The glob function would be used to obtain the list of files/directories w
3 min read
How to Get Current Date and Time using Python
In this article, we will cover different methods for getting data and time using the DateTime module and time module in Python. Different ways to get Current Date and Time using PythonCurrent time using DateTime objectGet time using the time moduleGet Current Date and Time Using the Datetime ModuleIn this example, we will learn How to get the curre
5 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 | Pandas Categorical DataFrame creation
pandas.DataFrame(dtype="category") : For creating a categorical dataframe, dataframe() method has dtype attribute set to category. All the columns in data-frame can be converted to categorical either during or after construction by specifying dtype="category" in the DataFrame constructor. Code : # Python code explaining # constructing categorical d
1 min read
Python | Matrix creation of n*n
Many times while working with numbers in data science we come across the problem in which we need to work with data science we need to transform a number to a matrix of consecutive numbers and hence this problem has a good application. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension List comprehen
5 min read
Python | Dictionary creation using list contents
Sometimes we need to handle the data coming in the list format and convert list into dictionary format. This particular problem is quite common while we deal with Machine Learning to give further inputs in changed formats. Let's discuss certain ways in which this inter conversion happens. Method #1 : Using dictionary comprehension + zip() In this m
5 min read
Memory Efficient Python List Creation in Case of Generators
We have the task of writing memory-efficient Python list creation in the case of Generators and printing the result. In this article, we will demonstrate memory-efficient Python list creation using Generators. What are Generators?Generators in Python are a type of iterable, allowing the creation of iterators in a memory-efficient manner. Unlike lis
3 min read
How To Get The Uncompressed And Compressed File Size Of A File In Python
We are given a compressed file as well as uncompressed file. Our task is to get the size of uncompressed as well as compressed file in Python. In this article, we will see how we can get the uncompressed and compressed file size of a file in Python. What is Uncompressed And Compressed File?Uncompressed File: An uncompressed file is a file that has
3 min read
Python - Get file id of windows file
File ID is a unique file identifier used on windows to identify a unique file on a Volume. File Id works similar in spirit to a inode number found in *nix Distributions. Such that a fileId could be used to uniquely identify a file in a volume. We would be using an command found in Windows Command Processor cmd.exe to find the fileid of a file. In o
3 min read
Practice Tags :
three90RightbarBannerImg