Set Windows System time to a file modification time.
- Python 3
- pywin32
- Open a command prompt (
cmd.exe) - Run script with the desired file path, e.g.:
mtime2system.py "C:\test_filename.txt"
| #!/usr/bin/env python | |
| import time | |
| import os.path | |
| import sys | |
| import win32api # http://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/ | |
| from datetime import datetime | |
| def get_mtime(file_path: str) -> datetime: | |
| timestamp = os.path.getmtime(file_path) | |
| return datetime.fromtimestamp(timestamp) | |
| def convert_local_time_to_utc(t: time.struct_time) -> time.struct_time: | |
| seconds = time.mktime(t) | |
| return time.gmtime(seconds) | |
| def set_system_time(new_date: datetime): | |
| local_time = new_date.timetuple() | |
| utc_time = convert_local_time_to_utc(local_time) | |
| win32api.SetSystemTime( | |
| utc_time.tm_year, utc_time.tm_mon, utc_time.tm_wday, utc_time.tm_mday, | |
| utc_time.tm_hour, utc_time.tm_min, utc_time.tm_sec, new_date.microsecond // 1000 | |
| ) | |
| def main(arguments: list): | |
| if len(arguments) < 1: | |
| print('Missing file path!', file=sys.stderr) | |
| return 1 | |
| file_path = arguments[0] | |
| try: | |
| file_mtime = get_mtime(file_path) | |
| except FileNotFoundError: | |
| print('File not exist: {!s}'.format(file_path), file=sys.stderr) | |
| return 1 | |
| set_system_time(file_mtime) | |
| print('System time successfully set to {!s}'.format(file_mtime)) | |
| return 0 | |
| if __name__ == '__main__': | |
| exit_code = main(sys.argv[1:]) | |
| sys.exit(exit_code) |