Python Module to Change System Date and Time

Python module to change system date and time

import sys
import datetime

time_tuple = ( 2012, # Year
9, # Month
6, # Day
0, # Hour
38, # Minute
0, # Second
0, # Millisecond
)

def _win_set_time(time_tuple):
import pywin32
# http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
# pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])

def _linux_set_time(time_tuple):
import ctypes
import ctypes.util
import time

# /usr/include/linux/time.h:
#
# define CLOCK_REALTIME 0
CLOCK_REALTIME = 0

# /usr/include/time.h
#
# struct timespec
# {
# __time_t tv_sec; /* Seconds. */
# long int tv_nsec; /* Nanoseconds. */
# };
class timespec(ctypes.Structure):
_fields_ = [("tv_sec", ctypes.c_long),
("tv_nsec", ctypes.c_long)]

librt = ctypes.CDLL(ctypes.util.find_library("rt"))

ts = timespec()
ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond

# http://linux.die.net/man/3/clock_settime
librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))

if sys.platform=='linux2':
_linux_set_time(time_tuple)

elif sys.platform=='win32':
_win_set_time(time_tuple)

I don't have a windows machine so I didn't test it on windows... But you get the idea.

How to change a system date with python on windows

In reference to the method win32api.SetSystemTime all the arguments must be of type integer.

import datetime
import win32api

now = datetime.datetime.now()
print (now)
tomorrow = now + datetime.timedelta(days = 8)
print (tomorrow)

year = int(tomorrow.year)
month = int(tomorrow.month)
# Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
dayOfWeek = int(tomorrow.weekday())
day = int(tomorrow.day)
hour = int(tomorrow.hour)
minute = int(tomorrow.minute)
second = int(tomorrow.second)
millseconds = int((tomorrow.microsecond)/1000)

win32api.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds)

output

Python module to set local time and date

The win32api module wraps SetSystemTime to take the SYSTEMTIME structure fields as 8 separate function parameters. The time should be passed as UTC. wDayOfWeek is ignored (i.e. pass it as 0).

The win32api module wraps SetLocalTime more conveniently and idiomatically. It takes a datetime.datetime instance instead of requiring separate parameters. For example:

import datetime
import win32api

dt = datetime.datetime(2018, 1, 4, 14, 30)
win32api.SetLocalTime(dt)

The Token of the calling process must have SeSystemtimePrivilege, so generally the user needs to be an elevated administrator.

Setting the system date in Python (on Windows)

You should be able to use win32api.SetSystemTime. This is part of pywin32.

Python script to reset date and time

After changing your system time, your computer only knows the new time. It does not "remember" the original time, so that's why time.gmtime() also returned the new time.

To have your computer learn what the real world time is again, the input has to come from somewhere outside your computer. You can either type in the current time manually, or you could write a script to call some time API service. I found several freely available ones by searching for "time api".

How to dynamicly update the date with the datetime module in python?

Make the file generation name into a function so that you can call it whenever/however you want as shown below.

ROOT_DIR = r'C:/Users/user/'
BASE_DIR = r'documents'
BACKUP_DIR = r'path/to/backups/folder/'
BACKUP_SUFFIX = 'docs_backup'

def make_backup_path():
now = datetime.now()
date = now.strftime("%Y-%m-%d_%H-%M-%S")
backup_path = BACKUP_DIR + date + BACKUP_SUFFIX
return backup_path

@sched.scheduled_job('interval', hours=1)
def zip_method():
#Make the backup archive every one hour
shutil.make_archive(
make_backup_path(),
'zip',
ROOT_DIR,
BASE_DIR)
print(date)
print("I did a backup!")

#This is to make the backup when the computer starts.
shutil.make_archive(
make_backup_path(),
'zip',
ROOT_DIR,
BASE_DIR)

sched.start()

Getting today's date in YYYY-MM-DD in Python?

Use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

To also include a zero-padded Hour:Minute:Second at the end:

>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'

To get the UTC date and time:

>>> datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-27 00:50:03'


Related Topics



Leave a reply



Submit