Algorithm
-
Import Modules:
- Import the necessary modules:
os
for operating system-related functions anddatetime
for handling dates.
- Import the necessary modules:
-
Define Function:
- Create a function, let's call it
get_file_dates
, that takes a file path as input.
- Create a function, let's call it
-
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.
- Get the file creation time using
-
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.
- Set a variable
- Provide an example to demonstrate how to use the function.
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
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
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
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
Last metadata change time or path creation time: 2021-04-12 10:43:24.234189
Demonstration
Python Programing Example to Get File Creation and Modification Date-DevsEnv