{"id":6474,"date":"2021-05-22T09:06:26","date_gmt":"2021-05-22T03:36:26","guid":{"rendered":"https:\/\/python-programs.com\/?p=6474"},"modified":"2021-11-22T18:53:39","modified_gmt":"2021-11-22T13:23:39","slug":"python-get-last-modification-date-time-of-a-file-os-stat-os-path-getmtime","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-get-last-modification-date-time-of-a-file-os-stat-os-path-getmtime\/","title":{"rendered":"Python : Get Last Modification date & time of a file. | os.stat() | os.path.getmtime()"},"content":{"rendered":"

Getting the Last Modification date & time of a file. | os.stat() | os.path.getmtime() in Python.<\/h2>\n

\u00a0<\/strong>We will see how we can get the modification date & time of a file and in our desired formats.<\/p>\n

Get last modification time of a file using os.stat( ) :<\/h3>\n
Syntax-os.stat(filePath)<\/pre>\n

The above function returns os.stat_result<\/code> that contains stats about the file .<\/p>\n

To get the modification time, we have to use the ST_MTIME<\/code><\/em> that will provide us with the modification time in seconds. We will pass it to a function time.ctime( )<\/code> <\/em>which will return the info in a readable manner.<\/p>\n

import os\r\nimport time\r\nimport stat\r\n#Path of the file\r\nfileStats = os.stat ( 'file.txt' )\r\n#Passing the stats so that we get it in a readable manner\r\nmodTime = time.ctime ( fileStats [ stat.ST_MTIME ] )\r\nprint(\"Modified Time : \", modTime )\r\n<\/pre>\n
Output :\r\nModified Time :\u00a0 Thu May 13 19:02:47 2021<\/pre>\n

Get last modification time of a file using os.path.getmtime() :<\/strong><\/p>\n

We can also use another one of python\u2019s os module function i.e. os.path.getmtime( )<\/code><\/p>\n

Syntax-os.path.getmtime( filePath)<\/pre>\n

The function returns the number of seconds elapsed after the modification of the file .We have to convert it into a proper format.<\/p>\n