Write a Python Program to Get File Creation and Modification Date

As a Python programmer, it is often necessary to get the creation and modification date of a file.

This information can be useful for organizing files, tracking changes, and more.

In this tutorial, we’ll discuss how to use Python to get the creation and modification date of a file.


Getting File Creation Date

To get the creation date of a file in Python, we can use the os.path.getctime() function.

This function takes a file path as its argument and returns the creation time of the file in seconds since the epoch.

Here’s an example:

import os
import datetime

file_path = 'path/to/file.txt'
creation_time = os.path.getctime(file_path)
print("Creation Time:", datetime.datetime.fromtimestamp(creation_time))

In this example, we first import the os and datetime modules.

We then define the file_path variable to the path of the file we want to get the creation date of.

We use the os.path.getctime() function to get the creation time of the file in seconds since the epoch.

Finally, we use the datetime.datetime.fromtimestamp() function to convert the creation time to a more readable format.

Getting File Modification Date

To get the modification date of a file in Python, we can use the os.path.getmtime() function.

This function takes a file path as its argument and returns the modification time of the file in seconds since the epoch.

Here’s an example:

import os
import datetime

file_path = 'path/to/file.txt'
modification_time = os.path.getmtime(file_path)
print("Modification Time:", datetime.datetime.fromtimestamp(modification_time))

In this example, we use the os.path.getmtime() function to get the modification time of the file in seconds since the epoch.

We then use the datetime.datetime.fromtimestamp() function to convert the modification time to a more readable format.


Conclusion

In this tutorial, we’ve discussed how to use Python to get the creation and modification date of a file.

We’ve shown how to use the os.path.getctime() and os.path.getmtime() functions to get the creation and modification time of a file in seconds since the epoch, and how to use the datetime.datetime.fromtimestamp() function to convert these times to a more readable format.

With these tools, you can easily get the creation and modification date of any file in your Python projects.