How can I set the last modified time of a file from python?
There are 2 ways to do this. One is the os.utime example which is required if you are setting the timestamp on a file that has no reference stats.
However, if you are copying the files with shutil.copy() you have a reference file. Then if you want the permission bits, last access time, last modification time, and flags also copied, you can use shutil.copystat() immediately after the shutil.copy() .
And then there is shutil.copy2 which is intended to do both at once.
To edit a file last modified field, use:
os.utime(r'C:\my\file\path.pdf', (1602179630, 1602179630))
💡 — Epoch is the number of seconds that have elapsed since January 1, 1970. see more
If you are looking for a datetime version:
import datetime import os def set_file_last_modified(file_path, dt): dt_epoch = dt.timestamp() os.utime(file_path, (dt_epoch, dt_epoch)) # . now = datetime.datetime.now() set_file_last_modified(r'C:\my\file\path.pdf', now)
Jossef Harush Kadouri 29702
Related Query
- How can I set the last modified time of a file from python?
- How do I get the time a file was last modified in Python?
- How can I determine the display idle time from Python in Windows, Linux, and MacOS?
- How can I stop python from converting a mySQL DATETIME to a datetime.date when the time is 00:00:00?
- Python How can I get the version number from a .whl file
- How can I copy from an html file to the clipboard in Python in formatted text?
- How can I dynamically get the set of classes from the current python module?
- How can I change the default newline character when reading lines from a file in Python 3?
- Where do I put the .so file from Boost.Python so I can import it as a module, and how do I use it with both Python 2 and 3
- How can I install packages using pip according to the requirements.txt file from a local directory?
- How can I extract the folder path from file path in Python?
- How can you set class attributes from variable arguments (kwargs) in python
- How to install Python packages from the tar.gz file without using pip install
- How can I make an EXE file from a Python program?
- How can I remove the ANSI escape sequences from a string in python
- How do I read two lines from a file at a time using python
- Python — How to extract the last x elements from a list
- Python — How can I pad a string with spaces from the right and left?
- How can I use the python HTMLParser library to extract data from a specific div tag?
- How to Reduce the time taken to load a pickle file in python
- How do I import from a file in the current directory in Python 3?
- Python — how can I get the class name from within a class method — using @classmethod
- How can I set the Python max allowed line length to 120 in Syntastic for Vim?
- How can I make setuptools (or distribute) install a package from the local file system
- How to get the file modification date in UTC from Python
- How can I access variables set in the Python nosetests setup function
- How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
- Python — How can I open a file and specify the offset in bytes?
- How to read lines from a file in python starting from the end
- Django: How can I check the last activity time of user if user didn’t log out?
- How can I minimize/maximize windows in macOS with the Cocoa API from a Python script?
- How to check the version of the python API at compile time from a C extension module?
- How can I keep python from loading the ‘wrong’ package?
- How to return unique words from the text file using Python
- How can I extract the call graph of a function from Python source files?
- How can I set the y axis in radians in a Python plot?
- How can I run my python script from the terminal in Mac OS X without having to type the full path?
- How do I check if the python debug option is set from within a script
- how to write the collections.Counter object to a file in python and then reload it from the file and use it as a counter object
- How can I convert the time in a datetime string from 24:00 to 00:00 in Python?
- How can I script the creation of a movie from a set of images?
- How can I properly set the `env.hosts` in a function in my Python Fabric `fabfile.py`?
- How can I strip the file extension from a list full of filenames?
- How can I create an Exception in Python minus the last stack frame?
- How can I start an interactive python/ipython session from the middle of my python program?
- How to download files from s3 given the file path using boto3 in python
- Kafka Consumer: How to start consuming from the last message in Python
- How to prevent a race condition when multiple processes attempt to write to and then read from a file at the same time
- How to download a file from Google Drive using Python and the Drive API v3
- How can I get the file size from a link without downloading it in python?
More Query from same tag
- Python XLWT adjusting column widths
- How to use spacy in large dataset with short sentences efficiently?
- How do I get the area of a GeoJSON polygon with Python
- Concatenating two tensors with different dimensions in Pytorch
- Bulk Upsert with SQLAlchemy Postgres
- Try — Except in Python for given amount of time
- how to type sudo password when using subprocess.call?
- Pydoop stucks on readline from HDFS files
- Applying callbacks in a custom training loop in Tensorflow 2.0
- Pycharm exit code 0
- How to load SVM data from file in OpenCV 3.1?
- Python @precondition / @postcondition for member function — how?
- Adding meta-information/metadata to pandas DataFrame
- PROJ pyproj conversion of point EPSG 4326 (WSG 84) to (EPSG 28992)
- Sqlalchemy: secondary relationship update
- How do I get mouse position relative to the parent widget in tkinter?
- WSGI: what’s the purpose of start_response function
- Why does «[] is [ ]» evaluate to False in python
- Lists sorting in Python (transpose)
- Pydev PyUnit issue when using thread.join to ensure all threads are joined
- How to return all the columns with flask-sqlalchemy query join from two tables
- Stripping off the seconds in datetime python
- How to make a python script «pipeable» in bash?
- how to iterate over all the objects in a PDF page and check which ones are text objects?
- Beautifulsoup sibling structure with br tags
- getting ValueError : «Can only tuple-index with a MultiIndex «
- What is the difference between Python vs Jython vs IronPython vs wxPython?
- Algorithm used to implement the Python str.count function
- How can I create a dead weakref in python?
- Saving SQLAlchemy models to file
- User based filtering:Recommendation system
- Python — Recommended way to dynamically add methods within a class
- What is the state of the art way to handle what makefiles do for python data analysis?
- How to get the width of text using Pygame
- OSError’s filename attribute unavailable?
Change File Modification Time In Python
This post demonstrates how to change a file modification time in Python. No third party modules are required and it will work on Windows, Mac and Linux.
File modification times show when a file was last edited. This can sometimes be confused with creation time but these are very different. Creation time is normally held by the operating system and states when a file was created. This means if you download a file from the internet, the creation time will change and be the time it was downloaded. Thus the creation time isn’t very helpful.
File modification time is different however as it is stored in the file. Even though the operating system still manages these, they can still be easily changed as opposed to creation time.
The modification date can be found by right-clicking on a file and selecting properties.
Setting File Modification Times
First, you will want to import os, time and datetime.
import os import time import datetime
You will now need to locate the file you want to edit and create a time object to set to the file. To create one, we will first break it down into its simpler parts.
fileLocation = r"" year = 2017 month = 11 day = 5 hour = 19 minute = 50 second = 0
fileLocation is a string and the rest of the variables above are integers.
Next, we will create our datetime object using the data given and then convert it to seconds since epoch; this is what will be stored.
date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) modTime = time.mktime(date.timetuple())
Now we can do a simple os.utime call passing the file and modification time to set the new times.
os.utime(fileLocation, (modTime, modTime))
Now if you go back and check the modification date it should be changed.
import os import time import datetime fileLocation = r"" year = 2017 month = 11 day = 5 hour = 19 minute = 50 second = 0 date = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second) modTime = time.mktime(date.timetuple()) os.utime(fileLocation, (modTime, modTime))
But how do I change creation time?
The solution is platform-specific but for Windows you can look at this.
Owner of PyTutorials and creator of auto-py-to-exe. I enjoy making quick tutorials for people new to particular topics in Python and tools that help fix small things.
How to set file modification time (mtime) in Python
You can use os.utime() to set the access and modification times of files in Python. In order to set just the access time ( mtime ) use this snippet:
# mtime must be a datetime stat = os.stat(filename) # times must have two floats (unix timestamps): (atime, mtime) os.utime(filename, times=(stat.st_atime, mtime.timestamp()))
Or use this utility function:
from datetime import datetime import os def set_file_modification_time(filename, mtime): """ Set the modification time of a given filename to the given mtime. mtime must be a datetime object. """ stat = os.stat(filename) atime = stat.st_atime os.utime(filename, times=(atime, mtime.timestamp()))
# Set the modification time of myfile.txt to 1980-1-1, leave the acess time intact set_file_modification_time("myfile.txt", datetime(1980, 1, 1, 0, 0, 0))
In case you need to compatible with Python 2.x, use this variant instead:
from datetime import datetime import os import time def datetime_to_timestamp(dt): return time.mktime(dt.timetuple()) + dt.microsecond/1e6 def set_file_modification_time(filename, mtime): """ Set the modification time of a given filename to the given mtime. mtime must be a datetime object. """ stat = os.stat(filename) atime = stat.st_atime os.utime(filename, (atime, datetime_to_timestamp(mtime)))
In case you have any option of using Python 3.x, I recommend using the Python 3 version listed above, since it’s much more readable, involves less code and (at the time of writing this code), Python 2 will be retired in only a couple of months. I recommend upgrading your scripts with Python 3 compatibility as soon as possible as many other projects have already done.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow
birkin / python_set_date.md
using python, how would I change a file creation-date for a pdf?
Modifying a file’s creation time isn’t a standard operation because it’s not a common need and it can potentially cause issues. However, it is possible to do this using the Python os and datetime modules, specifically using the os.utime function.
Here is a basic example of how you can change the creation date of a file:
import os import time import datetime # specify your file path filepath = '/path/to/your/file.pdf' # specify the creation date you want to set new_creation_time = datetime.datetime(2023, 5, 17, 0, 0) # convert the datetime object to a timestamp new_timestamp = time.mktime(new_creation_time.timetuple()) # change the creation date of the file os.utime(filepath, (new_timestamp, new_timestamp))
In this example, the creation time and modification time of the file at filepath are set to the timestamp equivalent of May 17, 2023, at 00:00.
- The os.utime function changes both the access time and the modified time. As far as I know, there’s no standard way in Python to change only the creation time of a file.
- This method will work on Unix systems (like Linux or MacOS). On Windows, it might not work as expected because Windows handles file timestamps differently. For Windows, you might need to use a platform-specific API to modify the creation time, such as pywin32.
- Changing file timestamps can have unexpected side effects, like affecting backups or causing issues with file synchronization, so it’s generally not recommended unless you have a specific reason for doing it.
- Make sure you have the appropriate permissions to modify the file.