Algorithm


  1. Import Modules:

    • Import the necessary modules: os for operating system-related functions and datetime for handling dates.
  2. Define Function:

    • Create a function, let's call it get_file_dates, that takes a file path as input.
  3. Try-Except Block:

    • Inside the function, use a try-except block to handle the case where the file is not found.
    • In the try block:
      • Get the file creation time using os.path.getctime.
      • Convert the creation time to a readable date format using datetime.datetime.fromtimestamp.
      • Get the file modification time using os.path.getmtime.
      • Convert the modification time to a readable date format.
      • Return the creation and modification dates.
  4. Example Usage:

    • Provide an example to demonstrate how to use the function.
      • Set a variable file_path with the path to the file you want to inspect.
      • Call the get_file_dates function with the file path.
      • Print the creation and modification dates.

 

Code Examples

#1 Code Example- Python Programing Using os module

Code - Python Programming

import os.path, time

file = pathlib.Path('abc.py')
print("Last modification time: %s" % time.ctime(os.path.getmtime(file)))
print("Last metadata change time or path creation time: %s" % time.ctime(os.path.getctime(file)))
Copy The Code & Try With Live Editor

Output

x
+
cmd
Last modification time: Mon Apr 12 10:43:24 2020
Last metadata change time or path creation time: Mon Apr 12 10:43:24 2020

#2 Code Example- Python Programing Using stat() method

Code - Python Programming

import datetime
import pathlib

fname = pathlib.Path('abc.py')
print("Last modification time: %s" % datetime.datetime.fromtimestamp(fname.stat().st_mtime))
print("Last metadata change time or path creation time: %s" % datetime.datetime.fromtimestamp(fname.stat().st_ctime))
Copy The Code & Try With Live Editor

Output

x
+
cmd
Last modification time: 2021-04-12 10:43:24.234189
Last metadata change time or path creation time: 2021-04-12 10:43:24.234189
Advertisements

Demonstration


Python Programing Example to Get File Creation and Modification Date-DevsEnv