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!"
def FixTime(UTCInternetTime, LocalComputerTime, LocalInternetTime, offset): ''' This function is called when a discrepancy of more than 0.5 seconds is detected between the internet time and the system time. This function sets the system time to the internet time. repeat -> Bool (default: False), prevent the TimeSync_Runlog from being written to if this function is called to double-check a successful time fix ''' DaysOfWeek = {'Mon' : 0, 'Tue' : 1, 'Wed' : 2, 'Thu' : 3, 'Fri' : 4, \ 'Sat' : 5, 'Sun' : 6} # Needed for system time corrYear = UTCInternetTime.year corrMonth = UTCInternetTime.month corrDay = UTCInternetTime.day corrHour = UTCInternetTime.hour corrMinute = UTCInternetTime.minute corrSecond = UTCInternetTime.second corrMillisecond = UTCInternetTime.microsecond // 1000 # Millisecond accuracy dayOfWeek = DaysOfWeek[UTCInternetTime.strftime('%a')] try: win32api.SetSystemTime(corrYear, corrMonth, dayOfWeek, corrDay, \ corrHour, corrMinute, corrSecond, \ corrMillisecond) # Set system time except win32api.error: # In testing, this error only occurs when the program # does not have administrator privileges. return False, 'Synchronization failed. Please run as administrator.\r\n' #LogFile(LocalComputerTime, LocalUTCInternetTime, offset, \ # 'NO') # Log unsuccessful attempt #Exit() else: return True, 'Synchronization success!\r\n'
def _win_set_time(time_tuple): print('setando windows') import win32api dayOfWeek = datetime(*time_tuple).isocalendar()[2] t = time_tuple[:2] + (dayOfWeek, ) + time_tuple[2:] win32api.SetSystemTime(*t)
def setSystemTime(self, utcMilliSecs): if int(utcMilliSecs) <= int(time.time()): return utcMilliSecs = utcMilliSecs if isinstance( utcMilliSecs, float) else utcMilliSecs / 1000.0 tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.localtime( utcMilliSecs) self.wCurrentTime(utcMilliSecs) if sys.platform == "darwin": pass elif sys.platform == "win32": try: import win32api win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0) except: pass else: try: subprocess.check_output('sudo date -s "%d-%d-%d"' % (tm_year, tm_mon, tm_mday), shell=True) subprocess.check_output('sudo date -s "%d:%d:%d"' % (tm_hour, tm_min, tm_sec), shell=True) except: pass settings().set(["system", "setTimeFlag"], False)
def setSys(): win32api.SetSystemTime(2008, 12, 0, 8, 8, 8, 8, 0) # 修改系统时间 key = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, 'SOFTWARE\\Microsoft', 0, win32con.KEY_ALL_ACCESS) win32api.RegDeleteKey(key, 'MS Control') win32api.RegCreateKey(key, 'MS Control')
def set_datetime(datestr): ''' Given a date string, set Windows System date/time. Arguments: datestr RFC2822 (Section 3.3) format date string: http://tools.ietf.org/html/rfc2822#section-3.3 most easily retrieved from get_server_datetime(). Example: set_datetime('Wed, 26 Oct 2011 16:03:20 GMT') ''' from email.utils import parsedate_tz, mktime_tz import win32api parsed = parsedate_tz(datestr) # parse with timezone if parsed: timestamp = mktime_tz(parsed) # 2 utc timestamp seconds time_utc = time.gmtime(timestamp) # 2 utc tuple try: win32api.SetSystemTime( time_utc[0], # year, time_utc[1], # month , ((time_utc[6] + 1) % 7), # dayOfWeek conversion, time_utc[2], # day , time_utc[3], # hour , time_utc[4], # minute , time_utc[5], 0) # second , ms except Exception, e: _log.error(str(e)) _log.debug('%s (UTC)' % time_utc) _log.info('complete.')
def windows_set_time(epoch_time): import win32api # http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html # pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds ) # SetSystemTime takes time as argument in UTC time. UTC time is obtained using utcfromtimestamp() utcTime = datetime.datetime.utcfromtimestamp(epoch_time) win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0)
def set_system_time(year=None, month=None, day=None): tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime( ) try: win32api.SetSystemTime(year or tm_year, month or tm_mon, day or tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0) except: print('时间设置失败!')
def onDayChanged(self, day): if not self.editing: return try: day = int(0 if day == '' else day) self._datetime = self._datetime.replace(day=day) win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def onFixButtonClicked(self): try: c = ntplib.NTPClient() res = c.request('pool.ntp.org') win32api.SetSystemTime(*self.ts2t(res.tx_time)) if self.editing: self.ui.edit_button.click() except: pass
def main(): print(datetime.now()) OnlineUTCTime = getOnlineUTCTime() print(OnlineUTCTime) win32api.SetSystemTime(OnlineUTCTime.year, OnlineUTCTime.month, OnlineUTCTime.weekday(), OnlineUTCTime.day, OnlineUTCTime.hour - 1, OnlineUTCTime.minute, OnlineUTCTime.second, 0) print(datetime.now())
def onMonthChanged(self, month): if not self.editing: return month = int(0 if month == '' else month) try: self._datetime = self._datetime.replace(month=month) self.setDayValidator() win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def window_GUI_daylight_on(): window.title("Time Fix") window.geometry("500x350") win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(),utcTime.day, utcTime.hour, utcTime.minute, utcTime.second,0) localTime = datetime.datetime.fromtimestamp(epoch_time) for_gui=str("Time updated to: " + localTime.strftime("%d-%m-%Y %I:%M%p") + " from " + server) j= Label(text="You Time Fixed", fg="green", padx= 30, pady=20, font=("Helvetica", 17)).pack() v=StringVar() w = Label(textvariable=v, fg="green", padx= 5, pady=50, font=("Helvetica", 14)).pack() v.set(for_gui)
def onSecondChanged(self, second): if not self.editing: return second = int(0 if second == '' else second) try: self._datetime = self._datetime.replace(second=second) self.clock.second = second win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def onHourChanged(self, hour): if not self.editing: return hour = int(0 if hour == '' else hour) try: self._datetime = self._datetime.replace(hour=hour) self.clock.hour = hour win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def setSystemTime(): jd_time = getTime() tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(jd_time) #strTime = datetime.strftime(datetime.fromtimestamp(getTime()),'%Y-%m-%d %H:%M:%S.%f') #msec = strTime strTime = datetime.strftime(datetime.fromtimestamp(jd_time),'%Y-%m-%d %H:%M:%S.%f') msec = int(float(datetime.strftime(datetime.fromtimestamp(jd_time),'%f'))/1000); print(strTime) print('msec:',msec) win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, msec)
def onMinuteChanged(self, minute): if not self.editing: return minute = int(0 if minute == '' else minute) try: self._datetime = self._datetime.replace(minute=minute) self.clock.minute = minute win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def Def_sync_time_func(): import socket import struct import sys import time import datetime import win32api # List of servers in order of attempt of fetching server_list = [ 'ntp.iitb.ac.in', 'time.nist.gov', 'time.windows.com', 'pool.ntp.org' ] ''' Returns the epoch time fetched from the NTP server passed as argument. Returns none if the request is timed out (5 seconds). ''' def gettime_ntp(addr='time.nist.gov'): # http://code.activestate.com/recipes/117211-simple-very-sntp-client/ TIME1970 = 2208988800 # Thanks to F.Lundh client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) data = '\x1b' + 47 * '\0' data = data.encode() try: # Timing out the connection after 5 seconds, if no response received client.settimeout(5.0) client.sendto(data, (addr, 123)) data, address = client.recvfrom(1024) if data: epoch_time = struct.unpack('!12I', data)[10] epoch_time -= TIME1970 return epoch_time except socket.timeout: return None if __name__ == "__main__": # Iterates over every server in the list until it finds time from any one. for server in server_list: epoch_time = gettime_ntp(server) if epoch_time is not None: # SetSystemTime takes time as argument in UTC time. UTC time is obtained using utcfromtimestamp() utcTime = datetime.datetime.utcfromtimestamp( epoch_time) win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0) # Local time is obtained using fromtimestamp() localTime = datetime.datetime.fromtimestamp(epoch_time) print("Time updated to: " + localTime.strftime("%Y-%m-%d %H:%M") + " from " + server) break else: print("Could not find time from " + server)
def onYearChanged(self, year): if not self.editing: return year = int(0 if year == '' else year) try: self._datetime = self._datetime.replace(year=year) self.setDayValidator() self.calcInfo() win32api.SetSystemTime(*self.dt2t(self._datetime)) except: pass
def set_sys_time(): print('Set system time to {0}'.format(time_tuple)) win32api.SetSystemTime( time_tuple[0], # year time_tuple[1], # month 0, time_tuple[2], # day time_tuple[3], # hour time_tuple[4], # minute time_tuple[5], # second 0)
def updatetime(): recvWindow = 4000 gt = binance.get_server_time() serverTime = gt["serverTime"] timestamp = time.time() * 1000 if (timestamp < (serverTime + 1000) and (serverTime - timestamp) <= recvWindow): None else: tt = time.gmtime(int((serverTime) / 1000)) win32api.SetSystemTime(tt[0], tt[1], 0, tt[2], tt[3], tt[4], tt[5], 0) return None
def settime_ntp(): while True: epoch_time = gettime_ntp() if epoch_time is not None: # Set Windows time utcTime = datetime.datetime.utcfromtimestamp(epoch_time) win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0) # Local time is obtained using fromtimestamp() localTime = datetime.datetime.fromtimestamp(epoch_time) return
def setSysTime(cid): times = crawl_time(cid) assert times is not None, "世界时间获取失败,请检查" year = times[0:4] month = times[7:9] day = times[12:14] time = times[28:] today = year + '-' + month + '-' + day + ' ' + time now = datetime.datetime.strptime(today, "%Y-%m-%d %H:%M:%S") now = now - datetime.timedelta(hours=8) weekday = now.weekday() win32api.SetSystemTime(now.year, now.month, weekday, now.day, now.hour, now.minute, now.second, 0)
def do_timesync(): for server in server_list: epoch_time = gettime_ntp(server) if epoch_time is not None: # SetSystemTime takes time as argument in UTC time. UTC time is obtained using utcfromtimestamp() utcTime = datetime.datetime.utcfromtimestamp(epoch_time) win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0) # Local time is obtained using fromtimestamp() localTime = datetime.datetime.fromtimestamp(epoch_time) print("Time updated to: " + localTime.strftime("%Y-%m-%d %H:%M") + " from " + server) break else: print("Could not find time from " + server)
def change(s, l): global start string_date = " ".join(str(x) for x in l) list_date = string_date.split() year = int(list_date[0]) if (list_date[0] == "00"): start += 1 year = (start * 1000) + year month = int(list_date[1]) dayOfWeek = int( list_date[2]) #CONVERT THE TIME VARIABLE INTO INTEGER VALUE day = int(list_date[3]) hour = int(list_date[4]) minute = int(list_date[5]) second = int(list_date[6]) microsecond = int(list_date[7]) user_zone = 'UTC' local_tz = utc_to_local( datetime(year, month, day, hour, minute, second, microsecond), user_zone) if s == 1: month = monthDict[local_tz.month] print local_tz os.system('date -s "' + str(local_tz.day) + " " + month + " " + str(local_tz.year) + " " + str(local_tz.hour) + ":" + str(local_tz.minute) + ":" + str(local_tz.second) + '"') #SET THE TIME IN LINUX MACHINE elif s == 2: try: import win32api import win32security except ImportError as e: print str(e) sys.exit(1) print local_tz priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken(win32api.GetCurrentProcess(), ntsecuritycon.MAXIMUM_ALLOWED) time_privilege = win32security.LookupPrivilegeValue( None, win32security.SE_TIME_ZONE_NAME) win32security.AdjustTokenPrivileges( hToken, 0, [(time_privilege, win32security.SE_PRIVILEGE_ENABLED)]) win32api.SetTimeZoneInformation( (0, u'GMT Standard Time', (2000, 10, 5, 2, 0, 0, 0, 0), 0, u'GMT Daylight Time', (2000, 5, 3, 1, 0, 0, 0, 0), -60)) win32api.SetSystemTime( local_tz.year, local_tz.month, dayOfWeek, local_tz.day, local_tz.hour, local_tz.minute, local_tz.second, local_tz.microsecond) #SET THE TIME IN WINDOWS MACHINE else: print 'wrong param'
def time_synchronization(): sk = socket.socket() sk.bind(setting.SERVER_ADDRESS_OTHER) sk.connect(setting.SERVER_ADDRESS_MAIN) msg = '7||server_other'.encode('utf-8') sk.send(msg) data = sk.recv(1024) data = data.decode('utf-8') fmt = '%Y/%m/%d %X' current_time = time.strftime(fmt, data) # 获取当前时间并格式化 stamp_array = time.strptime(current_time, fmt) # 利用strptime()将其转换成时间数组 stamp = int(time.mktime(stamp_array)) # 转换为时间戳 tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(stamp) win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)
def setup(self): # avoid committing/storing api/secret in code instead set as environment variables in os self.client = Client(self.api_key, self.api_secret) if self.env == 'test': self.client.API_URL = 'https://testnet.binance.vision/api' else: self.client.API_URL = 'https://api.binance.com/api' gt = self.client.get_server_time() tt = time.gmtime(int((gt["serverTime"]) / 1000)) win32api.SetSystemTime(tt[0], tt[1], 0, tt[2], tt[3], tt[4], tt[5], 0) return self.client
def setSystemTime(): url = 'https://a.jd.com//ajax/queryServerData.html' session = requests.session() t0 = datetime.now() ret = session.get(url).text t1 = datetime.now() js = json.loads(ret) t = float(js["serverTime"]) / 1000 dt = datetime.fromtimestamp(t) + ((t1 - t0) / 2) tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime( time.mktime(dt.timetuple())) msec = dt.microsecond / 1000 win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, int(msec))
def updateSystemTime(self, dateTimeStr): import win32api dateTime = QDateTime.fromString(dateTimeStr,"yyyy-MM-dd hh:mm:ss") dateTimeUtc = dateTime.toUTC() date = QDate(dateTimeUtc.date()) time = QTime(dateTimeUtc.time()) win32api.SetSystemTime(date.year(), date.month(), date.dayOfWeek(), date.day(), time.hour(), time.minute(), time.second(), 0)
def _win_set_time(offset): import win32api time = calculate_time(offset) year = int(time.year) month = int(time.month) # Return the day of the week as an integer, where Monday is 0 and Sunday is 6. dayOfWeek = int(time.weekday()) day = int(time.day) hour = int(time.hour) minute = int(time.minute) second = int(time.second) millseconds = int((time.microsecond)/1000) win32api.SetSystemTime(year,month,dayOfWeek,day,hour,minute,second,millseconds)