- Python Get File Creation and Modification DateTime
- Table of contents
- How to Get File Modification and Creation Time in Python
- Example to Get File Modification and Creation Time
- Get File Creation Datetime on Mac and Unix Systems
- Pathlib Module to Get the Creation and Modification Datetime of a file
- Example
- About Vishal
- Related Tutorial Topics:
- Python Exercises and Quizzes
- Получение даты создания и изменения файла в Python
Python Get File Creation and Modification DateTime
There are multiple ways to get file creation and modification datetime in Python. We will use the following methods of an OS and pathlib module to get file modification and creation time in Python.
os.path module:
- os.path.getmtime(path) : Cross-platform way to get file modification time in Python. It returns the Unix timestamp of when the file was last modified.
- os.path.getctime(‘file_path’) : To get file creation time but only on windows.
- os.stat(path).st_birthtime : To get file creation time on Mac and some Unix based systems.
Pathlib module:
- pathlib.Path(‘file_path’).stat().st_mtime : Best cross-platform way to get file modification time in Python.
- pathlib.Path(‘file_path’).stat().st_ctime : To get file creation time but only on windows and recent metadata change time on Unix
Table of contents
How to Get File Modification and Creation Time in Python
The below steps show how to use the os.path module and datetime module to get the creation and modification time of a file in Python.
- Import os.path module and datetime module The os.path module implements some valuable functions on pathnames. It is helpful to get the metadata of a file.
Example to Get File Modification and Creation Time
import datetime import os # Path to the file path = r"E:\demos\files_demos\sample.txt" # file modification timestamp of a file m_time = os.path.getmtime(path) # convert timestamp into DateTime object dt_m = datetime.datetime.fromtimestamp(m_time) print('Modified on:', dt_m) # file creation timestamp in float c_time = os.path.getctime(path) # convert creation timestamp into DateTime object dt_c = datetime.datetime.fromtimestamp(c_time) print('Created on:', dt_c)
Modified on: 2021-07-02 16:47:50.791990 Created on: 2021-06-30 17:21:57.914774
Note: If you want to represent datetime in different formats see Python Datetime formatting.
Get File Creation Datetime on Mac and Unix Systems
- On Mac, as well as some Unix based systems, you can use the st_birthtime attribute of a os.stat() or ( fsta()/lstat()) to function get the file creation time.
- But, the st_birthtime attribute of a os.stat() isnt’ guaranteed to be available on all systems such as linux.
- We need to convert the the integer tmestamp returned by the st_birthtime to a datetime object using datetime.datetime.fromtimestamp() .
import os import datetime # Path to the file path = r"/Users/myfiles/sample.txt" # get file creation time on mac stat = os.stat(path) c_timestamp = stat.st_birthtime c_time = datetime.datetime.fromtimestamp(c_timestamp) print(c_time)
Pathlib Module to Get the Creation and Modification Datetime of a file
From Python 3.4 onwards, we can use the pathlib module, which provides a wrapper for most OS functions. This module offers classes representing filesystem paths with semantics appropriate for different operating systems.
Let’s see how to use the pathlib module and datetime module to get the creation and modification Datetime of a file in Python.
Import pathlib module and datetime module:
- Pathlib module offers classes and methods to handle filesystem paths and get data related to files for different operating systems.
- DateTime module used to convert the creation and modification time returned by the pathlib module to human-readable format (dd-mm-YYYY HH:MM:SS).
Use pathlib.Path(‘file path’) to construct a file path
The absolute or relative path of a file. Use pathlib.Path() class to create a concrete path (location of the file) of the system’s path flavor. it will return the file path object.
It is a cross-platform implementation. For example, If you execute this on windows, you will get the instance of class ‘pathlib.WindowsPath.’
Use the stat() method of a pathlib object
To get the creation and modification time of a file, use the stat( ) method of a pathlib object. This method returns the metadata and various information related to a file, such as file size, creation, and modification time.
- Use the stat().st_mtime() to get the last content modification time in seconds
- stat().st_ctime (Platform dependent):
- the time of most recent metadata changes on Unix,
- the time of creation on Windows is expressed in seconds.
Wrap creation and modification time in a datetime object.
The datetime returned by the st_mtime() and s t_ctime() are in a numeric timestamp format. Use the fromtimestamp() method to format it in a human-readable format (dd-mm-YYYY HH:MM:SS)
Example
import datetime import pathlib # create a file path f_name = pathlib.Path(r'E:\demos\oop_demos\test.txt') # get modification time m_timestamp = f_name.stat().st_mtime # convert ti to dd-mm-yyyy hh:mm:ss m_time = datetime.datetime.fromtimestamp(m_timestamp) print(m_time) # get creation time on windows c_timestamp = f_name.stat().st_ctime c_time = datetime.datetime.fromtimestamp(c_timestamp) print(c_time)
2021-12-24 13:35:41.257598 2021-12-24 13:35:41.257598
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
- 15+ Topic-specific Exercises and Quizzes
- Each Exercise contains 10 questions
- Each Quiz contains 12-15 MCQ
Получение даты создания и изменения файла в Python
Существуют случаи, когда возникает потребность получить информацию о дате создания и последнего изменения файла. Это может быть полезно во многих контекстах, например, при создании скриптов для автоматического архивирования файлов или при работе с системами управления версиями.
В Python есть несколько способов получить эту информацию, причем большинство из них являются кросс-платформенными и будут работать как на Linux, так и на Windows.
Самый простой и распространенный способ — использование встроенного модуля os . Этот модуль содержит функцию os.path.getmtime() , которая возвращает время последнего изменения файла в виде числа с плавающей точкой, представляющего секунды с начала эпохи (обычно это 01.01.1970 г.).
import os filename = "test.txt" mtime = os.path.getmtime(filename) print(mtime)
Этот код вернет время последнего изменения файла «test.txt». Чтобы преобразовать это время из секунд с начала эпохи в более читаемый формат, можно использовать функцию datetime.fromtimestamp() :
import os from datetime import datetime filename = "test.txt" mtime = os.path.getmtime(filename) mtime_readable = datetime.fromtimestamp(mtime) print(mtime_readable)
Получение времени создания файла немного сложнее и отличается в зависимости от операционной системы. На Windows можно использовать функцию os.path.getctime() , которая работает аналогично os.path.getmtime() , но возвращает время создания файла. На Linux, к сожалению, такой функции нет, поэтому придется использовать функцию os.stat() , которая возвращает объект с метаданными файла, включая время его создания.
import os from datetime import datetime filename = "test.txt" stat = os.stat(filename) ctime = stat.st_ctime ctime_readable = datetime.fromtimestamp(ctime) print(ctime_readable)
Таким образом, получение информации о времени создания и изменения файла в Python — это относительно простая задача, которая может быть выполнена с помощью встроенного модуля os .