Gary Oldfaber
Gary Oldfaber

Reputation: 1702

Setting the system date in Python (on Windows)

There appears to be many packages for getting/formatting the current date, or finding out the date n time intervals from now. But I must be overlooking the existence of a simple method to set the date (like Windows' date.exe) in Python.

Surely such a function exists? I've been unable to find anything on Google, the python docs (datetime, time, os, etc) or stack overflow. TIA.

edit: To summarize,this page tells you how to get them.

And you can set them using either

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

or

os.system("date " + mm/dd/yy)

date.exe also appears to accept mm-dd-yy, 4-digit years, and probably other alternatives.

I prefer the latter for simplicity.

Upvotes: 6

Views: 17224

Answers (4)

MD Kawsar
MD Kawsar

Reputation: 437

import datetime
import pywin32
import pywintypes

# Set the new time (year, month, day, hour, minute, second)
new_time = datetime.datetime(2023, 8, 8, 15, 30, 0)

# Get the system time settings
system_time = pywintypes.SYSTEMTIME(
    year=new_time.year,
    month=new_time.month,
    day_of_week=new_time.weekday(),
    day=new_time.day,
    hour=new_time.hour,
    minute=new_time.minute,
    second=new_time.second,
    millisecond=0
)

# Set the system time (requires administrative privileges)
pywin32.SetSystemTime(system_time)

print("System time changed successfully.")

Upvotes: 0

sametatila
sametatila

Reputation: 56

on Windows you can use basically os for this

get date:

os.system("date")

get time:

os.system("time")

set date:

os.system("date "+str(mm-dd-yyyy))

set time:

os.system("time "+str(hh:mm:ss.ms))

You should run the script as administrator with whatever you use cmd, vscode etc.

Upvotes: 0

Martin
Martin

Reputation: 10563

Can you not use os.system("shell_cmd_in_here") to call the linux cmd:

date -s "2 OCT 2010 18:00:00"

This would set the system date to: 2 Oct 2010 18:00:00 for example.

So altogether it is:

os.system('date -s "2 OCT 2010 18:00:00"')

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284806

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

Upvotes: 4

Related Questions