Skip to content

Instantly share code, notes, and snippets.

@andras-tim
Last active January 13, 2016 02:31
Show Gist options
  • Save andras-tim/12fec20f70df49a8b024 to your computer and use it in GitHub Desktop.
Save andras-tim/12fec20f70df49a8b024 to your computer and use it in GitHub Desktop.
mtime2system - Set Windows System time to a file modification time

mtime2system

Set Windows System time to a file modification time.

Requirements

Use

  1. Open a command prompt (cmd.exe)
  2. 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment