Python check file date

Python : How to get Last Access & Creation date time of a file

In this article we will discuss different ways to get the last access and creation timestamp of a file and how to convert them into different formats.

os.stat()

Python’s os module provides a function os.stat()

It accepts the path of file as argument and returns the status of file in the form of an os.stat_result object. It contains many information related to the file like it’s mode, link type, access or modification time etc.

Frequently Asked:

Get Last Access time of a file using os.stat()

To get the last access time from os.stat_result object, access the property ST_ATIME, that contains the time of
most recent access in seconds. Then we can covert that to readable format using time.ctime i.e.

# get the the stat_result object fileStatsObj = os.stat ( filePath ) # Get last access time accessTime = time.ctime ( fileStatsObj [ stat.ST_ATIME ] )

Contents of accessTime in string will be,

Get Creation time of a file using os.stat()

To get the creation time from os.stat_result object access the property ST_CTIME. Information it provides is platform dependent i.e.

Then we can covert that to readable format using time.ctime i.e.

# get the the stat_result object fileStatsObj = os.stat ( filePath ) # Get the file creation time creationTime = time.ctime ( fileStatsObj [ stat.ST_CTIME ] )

Contents of creationTime in string will be,

Get File Last Access time using os.path.getatime()

Python’s os.path module provides an another API for fetching the last access time of a file i.e.

Here, path represents the path of file and it returns the last access time of file in terms of number of seconds since the epoch. Then we can convert the times since epoch to different readable format of timestamp. Let’s see an example,

# Get last access time of file in seconds since epoch accessTimesinceEpoc = os.path.getatime(filePath) # convert time sinch epoch to readable format accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(accessTimesinceEpoc))

Contents of last access time in string will be,

Читайте также:  Csv файл создать php файл

Here, time.localtime() converts the seconds since epoch to a struct_time in local timezone. Then by passing that time struct to time.strftime() we can get timestamp in readable format.
By changing format string in time.strftime() we can get date only and also in other format specific to our application.

We can also get the last access time in UTC timezone using time.gmtime() instead of time.localtime() i.e.

accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(accessTimesinceEpoc))

Contents of accessTime in string will be,

Get File creation time using os.path.getctime()

Python’s os.path module provides an another API for fetching the creation time of a file i.e.

Here, path represents the path of file and information it returns is platform dependent i.e.

Then we can convert the times since epoch to different readable format of timestamp. Let’s see an example,

# Get file creation time of file in seconds since epoch creationTimesinceEpoc = os.path.getctime(filePath) # convert time sinch epoch to readable format creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(creationTimesinceEpoc))

Contents of creationTime in string will be,

time.localtime() converts the seconds since epoch to a struct_time in local timezone and time.strftime() converts time struct to a readable format provided.

Get File creation time using os.path.getctime() in UTC Timezone

creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(creationTimesinceEpoc))

Contents ofcreationTime in string will be,

time.gmtime() converts the seconds since epoch to a struct_time in UTC timezone.

Complete example is as follows,

import os import stat import time def main(): filePath = '/home/varung/index.html' print("**** Get File Last Access time using os.stat() ****") # get the the stat_result object fileStatsObj = os.stat ( filePath ) # Get last access time accessTime = time.ctime ( fileStatsObj [ stat.ST_ATIME ] ) print("File Last Access Time : " + accessTime) print("**** Get File Creation time using os.stat() *******") # get the the stat_result object fileStatsObj = os.stat ( filePath ) # Get the file creation time creationTime = time.ctime ( fileStatsObj [ stat.ST_CTIME ] ) print("File Creation Time : " + creationTime) print("**** Get File Last Access time using os.path.getatime() ****") # Get last access time of file in seconds since epoch accessTimesinceEpoc = os.path.getatime(filePath) # convert time sinch epoch to readable format accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(accessTimesinceEpoc)) print("File Last Access Time : " + accessTime) print("**** Get File Last Access time using os.path.getatime() in UTC Timezone****") accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(accessTimesinceEpoc)) print("File Last Access Time : " + accessTime + ' UTC' ) print("**** Get File creation time using os.path.getctime() ****") # Get file creation time of file in seconds since epoch creationTimesinceEpoc = os.path.getctime(filePath) # convert time sinch epoch to readable format creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(creationTimesinceEpoc)) print("File Creation Time : " + creationTime ) print("**** Get File creation time using os.path.getctime() in UTC Timezone ****") creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(creationTimesinceEpoc)) print("File Creation Time : ", creationTime , ' UTC' ) if __name__ == '__main__': main()
**** Get File Last Access time using os.stat() **** File Last Access Time : Sun Oct 21 10:10:40 2018 **** Get File Creation time using os.stat() ******* File Creation Time : Sun Oct 21 10:10:40 2018 **** Get File Last Access time using os.path.getatime() **** File Last Access Time : 2018-10-21 10:10:40 **** Get File Last Access time using os.path.getatime() in UTC Timezone**** File Last Access Time : 2018-10-21 04:40:40 UTC **** Get File creation time using os.path.getctime() **** File Creation Time : 2018-10-21 10:10:40 **** Get File creation time using os.path.getctime() in UTC Timezone **** ('File Creation Time : ', '2018-10-21 04:40:40', ' UTC')

Источник

Читайте также:  Error invalid argument in javascript

Получение даты создания и изменения файла в 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 .

Источник

Оцените статью