LeanMan
LeanMan

Reputation: 524

How to invoke NTP sync from python on windows?

I've tried the following code

import os
os.system('w32tm /resync')

But the result was

The following error occurred: The service has not been started. (0x80070426)

I'm pretty sure the time service was started on a prior run by itself so this was odd - maybe it doesn't automatically run in-between restarts but then I'm not sure how it started before. In any case, running Net start w32time solved the not running issue. But then from the python script I get:

Sending resync command to local computer
The following error occurred: Access is denied. (0x80070005)

I'd like for my script to be able to run ntp sync whenever I detect time issue from my application so that the application can control its destiny but I also would like to keep privileges where they are without having to elevate privileges to get the command to work. I looked into ntplib and I don't think it offers resyncing functions but ability to query time from time servers. A workaround is to run an external task that continues to resync a defined period.

Is there a way to run a NTP sync command from my script instead? Machine is windows 10.

Upvotes: 1

Views: 3275

Answers (2)

AididDev
AididDev

Reputation: 1

1.Open the Start menu and search for "services".
2.Click on the "Services" app that appears in the search results.
3.In the Services window, scroll down to find the "Windows Time" service.
4.Right-click on the "Windows Time" service and select "Properties".
5.In the Properties window, set the "Startup type" to "Automatic" and click on "Apply".
6.If the service is not running, click on the "Start" button to start it.

Once the Windows Time service is running, you can run the Python code to synchronize the system clock

import os

# Run w32tm command to synchronize time
os.system('w32tm /resync')

Note that you may need to run this code with administrative privileges to make changes to the system clock.

Upvotes: 0

NotARobot011010
NotARobot011010

Reputation: 11

I have had the same issue and found a workaround through Windows 10 settings.

Found an answer from https://superuser.com/questions/529367/automatically-sync-windows-time-more-often-than-default

Although using ForceSynchronizeTime instead of SynchronizeTime worked for me:

Go to Control Panel > Administrative Tools > Task scheduler

left is an folder tree, expand: Task scheduler library > Microsoft > Windows > Time synchonization

right click the task: ForceSynchronizeTime > properties

Go to the triggers tab and click new, then select 'one time', check box 'repeat task every:', select how often and if to run it indefinetly.

The minimum duration is 5 minutes, but you could make multiple triggers starting at slightly different times if you want it to run more often than that.

Upvotes: 1

Related Questions