Skip to content
Fix Code Error

How to get file creation & modification date/times in Python?

March 13, 2021 by Code Error
Posted By: Mark Biek

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

What’s the best cross-platform way to get file creation & modification date/times in Python?

Solution

In Python 3.4 and above, you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.

>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}'  # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)

For more information about what os.stat_result contains, refer to the documentation. For the modification time you want fname.stat().st_mtime:

>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)

If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime:

>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)

This article has more helpful info and examples for the pathlib module.

Answered By: Anonymous

Related Articles

  • How can I check file size in Python?
  • When I'm testing a web app by JUnit and Mockito I…
  • Get operating system info
  • Svelte - how to wait for data that is being passed…
  • How to install the Raspberry Pi cross compiler on my…
  • Polymer conflict with moment.js?
  • Polymer Data Binding within custom element
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Can Windows Containers be hosted on linux?
  • Python is not calling fucntions properly
  • C how to find executable files only within given directory?
  • How do you get a directory listing sorted by…
  • Bash scripting, multiple conditions in while loop
  • Check synchronously if file/directory exists in Node.js
  • How do i calculate total without manually inputting it?
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • Webpack: Unable to find module with ID: main --…
  • using d3.js with aurelia framework
  • How to parse JSON file with Spring
  • Dafny prove lemmas in a high-order polymorphic function
  • ClassNotFoundException thrown
  • Get parent of current directory from Python script
  • Error: the entity type requires a primary key
  • Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap
  • Polymer: firebase DB not updating using firebase-element
  • How to use html template with vue.js
  • How can I create directory tree in C++/Linux?
  • How to calculate probability in a normal…
  • changing code from fs to fs-extra using node js
  • Add newly created specific folder to .gitignore in Git
  • What is your most productive shortcut with Vim?
  • How do I use Assert.Throws to assert the type of the…
  • Vue: How do you add E2E tests after not including…
  • How can I safely create a nested directory?
  • Can you change what a symlink points to after it is created?
  • Compiler error: "class, interface, or enum expected"
  • vuejs v2.0 pass data to component
  • Python File Error: unpack requires a buffer of 16 bytes
  • How can I iterate over files in a given directory?
  • Ember.js - where should interface state be stored?
  • What is the difference between Cygwin and MinGW?
  • How can I find the product GUID of an installed MSI setup?
  • How to delete a file or folder?
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Usage of __slots__?
  • What are the calling conventions for UNIX &…
  • What are the undocumented features and limitations…
  • Elegant ways to support equivalence ("equality") in…
  • Backbone.js - relationship between a View and Model?
  • Ember JS tutorial: TypeError: Cannot read property…
  • Using CTE in Oracle SQL (ORA-00923: FROM keyword not…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to use glob() to find files recursively?
  • SVG Mask is "bleeding" on canvas edges
  • How to make the overflow CSS property work with…
  • ComboBox.SelectedItem giving Null value
  • 'No JUnit tests found' in Eclipse
  • What is an application binary interface (ABI)?
  • How I can resolve exception…
  • How to get all of the immediate subdirectories in Python
  • 'equal' is not defined : Ember-qunit does not seem…
  • How can I view the source code for a function?
  • Virtual Memory Usage from Java under Linux, too much…
  • Instance initializer unit test fails with "store is…
  • How to connect to a docker container from outside…
  • Calculating a directory's size using Python?
  • Changing PowerShell's default output encoding to UTF-8
  • How do you write a reactive statement in…
  • why webpack4 production bundle will always include…
  • Programmatically generate url from path and params
  • SQL Query for Student mark functionality
  • How to print a date in a regular format?
  • Changing Icon Color behind ListTile in an…
  • How can I change color of date on the datepicker vuetify?
  • What's the difference between eval, exec, and compile?
  • How does PHP 'foreach' actually work?
  • Reading file using relative path in python project
  • Set up adb on Mac OS X
  • Is there a way with python to move files on windows…
  • Python: importing a sub‑package or sub‑module
  • Can't install via pip because of egg_info error
  • What does if __name__ == "__main__": do?
  • JavaScript unit test tools for TDD
  • How is to get a value down in the widget build other…
  • How do I get the full path of the current file's directory?
  • Text editor to open big (giant, huge, large) text files
  • What is “assert” in JavaScript?
  • What is the "assert" function?
  • Smart way to truncate long strings
  • What is a NullReferenceException, and how do I fix it?
  • Logging best practices
  • What is the use of "assert"?
  • PHP - Failed to open stream : No such file or directory
  • Unhandled Promise Rejection when trying to call…
  • Loading cross-domain endpoint with AJAX
  • Trying to read files in directory, directory just…
  • Examples of GoF Design Patterns in Java's core libraries
  • SameSite warning Chrome 77
  • Unit testing async functions in Ember controllers
  • Aligning equations with multiple marks and lineups…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

What is the purpose of the word ‘self’?

Next Post:

trying to align html button at the center of the my page

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error