Wednesday, July 3, 2024
HomeLanguagesPythonHow to get file creation and modification date or time in Python?

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

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

Using time module to get file creation & modification date or time in Python

We will use getctime() and getmtime() function, found inside the path module in the os library, for getting the creation and modification times of the file. Both the above functions return time in seconds since EPOCH (00:00:00 UTC on 1 January 1970) (time is of float datatype). Since that number doesn’t resemble an understandable timestamp, we would have to convert that time, i.e. it becomes recognizable. For that purpose, we would be using ctime() function found inside the time library.

Example 1: Converting the time in seconds to a timestamp

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: Timestamp 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 Get file creation & modification date or time in Python

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 really working with objects rather than strings or timestamps.

Example 1: Get Create And Modification Time Of a File Using os.path.getmtime

Python’s os.path module, a submodule of the OS module, is used to manipulate common path names. Python’s os.path.getmtime() method can be used to determine when the given path was last modified.

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 Create And Modification Time Of a File Using pathlib.Path

os.path module is a submodule of the os module in Python used for common path name manipulation. Return an os.stat result object, similar to os.stat, that contains details about this path.

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

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments