Both methods python script to set the system time

This article is to share a method script to set the system time two python, for your reference, as follows

The first method, when the system time provided with Python, i.e., the correction to the system

# The computer time used for some time, the system time allowed, and want to update the look 
 
# in windows inside, update the system time, often fail, and the speed is very busy. 
 
# Code online copy, find useful, than the windows from achieved with faster. 
# - * - Coding: UTF-. 8 - * - 
  
Import Socket
 Import struct
 Import time
 Import Win32API 
  
the TimeServer = ' be input the blank '  # national time Service Center IP 
Port = 123 DEF the getTime (): 
  TIME_1970 = 2208988800L 
  Client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 
  Data = ' \ X1B ' + 47 * ' \ 0
  
'
  client.sendto(data, (TimeServer, Port))
  data, address = client.recvfrom(1024)
  data_result = struct.unpack('!12I', data)[10]
  data_result -= TIME_1970
  return data_result
  
def setSystemTime():
  tm_year, tm_mon, tm_mday, 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 %d:%d:%d" % time.localtime(getTime())[:6]

 

Very fast, just double-click on it Py file

The second method, Python third party libraries recommended by ntplib on windows time synchronization
many times we have to correct synchronization script by Beijing's demand.
On linux synchronization time more convenient to install a software ntpdate on the line.
But more troublesome at times to synchronize the windows.
Then think of is to get an accurate time from a network, and then call the dos command to change the time.
Where to get it? Of course, when the National Service Center.
URL Time Service Center is cn.pool.ntp.org (note that widespread 210.72.145.44 This ip has expired, the direct use of the domain name.)
But it needs time ntp protocol from the Center for timing resolution.
ntplib is more do's.
Also worth mentioning is the change date and time in dos to be achieved through two commands, date command to change the date, time command to change the time.

Installation ntplib:

easy_install ntplib或pip install ntplib

Here the code.

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))

 

That's all for this article two python script to set the system time way, you learn it?

Guess you like

Origin www.cnblogs.com/ding5688/p/10978265.html