This article mainly introduces two methods for setting the system time using python scripts. One is to call socket to directly send udp packets to the National Time Service Center, and the other is to call the ntplib package, interested friends can refer to this article to share with you two methods for setting the system time using python scripts. The specific content is as follows:
The first method,Use Python to set the system time, that is
# After a period of time on the computer, the system time is not allowed. I want to update it. # in windows, updating the system time often fails and the speed is very busy. # The Code copied on the Internet is very useful and faster than the built-in implementation of windows. #-*-coding: UTF-8-*-import socket import struct import time import win32api TimeServer = '2017. 72.145.44 '# ip Port of the National Time Service Center = 123 def getTime (): TIME_1970 = 2208988800L client = socket. socket (socket. AF_INET, socket. SOCK_DGRAM) data = '\ x1b' + 47 * '\ 0' client. sendto (data, (TimeServer, Port) data, address = clie Nt. recvfrom (1024) data_result = struct. unpack ('! 12i', data) [10] data_result-= TIME_1970 return data_result def setSystemTime (): tm_year, tm_mon, average, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time. gmtime (getTime () win32api. setSystemTime (tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0) print "Set System OK! "If _ name _ = '_ main _': setSystemTime () print" % d-% d: % d "% time. localtime (getTime () [: 6]
Fast, just double-click the Py file.
Method 2,Recommended third-party python library, synchronize time on windows through ntplib
Most of the time, we have the need to use a script to synchronize and correct Beijing time.
The synchronization time on linux is convenient. Just install the ntpdate software.
However, it is troublesome to synchronize time in windows.
In this case, you can obtain an accurate time from the network and then call the doscommand to modify the time.
Where can I get it? Of course, it is the national Time Service Center.
The website of the Time Service Center is cn.pool.ntp.org (note that the widely spread 210.72.145.44 ip Address has expired and the domain name is used directly .)
However, the time obtained from the time service center must be parsed using the ntp protocol.
Ntplib does this.
It is also worth mentioning that the dos modification date must be implemented through two commands, the date command to modify the date and the time command to modify the time.
Install ntplib:
Easy_install ntplib or pip install ntplib
The code below.
import os import time import ntplib c = ntplib.NTPClient() response = c.request('pool.ntp.org') ts = response.tx_time _date = time.strftime('%Y-%m-%d',time.localtime(ts)) _time = time.strftime('%X',time.localtime(ts)) os.system('date {} && time {}'.format(_date,_time))
The above is all the content in this article. Have you learned how to set the system time using two python scripts?