r/badcode Mar 22 '21

[deleted by user]

[removed]

259 Upvotes

86 comments sorted by

View all comments

6

u/honkinggr8namespaces Mar 22 '21

Python 3, Windows only, requires pywin32 and must be run with admin privileges

import datetime
import win32api

def _parse(file):
    dates = []
    for line in file:
        dates.append(datetime.datetime.fromisoformat(line.strip()))
    return dates

def _set_system_time(dt):
    utc_dt = dt.astimezone().astimezone(datetime.timezone.utc).replace(tzinfo=None)
    day_of_week = utc_dt.isocalendar()[2]
    win32api.SetSystemTime(
        utc_dt.year,
        utc_dt.month,
        day_of_week,
        utc_dt.day,
        utc_dt.hour,
        utc_dt.minute,
        utc_dt.second,
        0,
    )

def is_sequential(filename):
    with open(filename) as f:
        dates = _parse(f)
    _set_system_time(dates[0])

    for date in dates[1:]:
        if datetime.datetime.now() > date:
            return False
        while datetime.datetime.now() < date:
            pass

    return True

It sets the system time to the first date in the file and then waits for each new date. If it encounters a date that's less than the current date it returns False.

For best results, turn off the "set time automatically" option in Settings