def main(): """ Entry point for ntpclient.py. """ args = setup() t1 = time.clock_gettime(time.CLOCK_REALTIME) ntptime = get_ntp_time(args.server) t4 = time.clock_gettime(time.CLOCK_REALTIME) # It is not guaranteed that the NTP time is *exactly* in the middle of both # local times. But it is a reasonable simplification. roundtrip = round(t4 - t1, 4) localtime = (t1 + t4) / 2 diff = localtime - ntptime res = None if os.geteuid() == 0: time.clock_settime(time.CLOCK_REALTIME, ntptime) res = "Time set to NTP time." localtime = datetime.fromtimestamp(localtime) ntptime = datetime.fromtimestamp(ntptime) if not args.quiet: print(f"Using server {args.server}.") print(f"NTP call took approximately {roundtrip} s.") print("Local time value:", localtime.strftime("%a %b %d %H:%M:%S.%f %Y.")) print( "NTP time value:", ntptime.strftime("%a %b %d %H:%M:%S.%f %Y."), "±", roundtrip / 2, "s.", ) print(f"Local time - ntp time: {diff:.6f} s.") if res: print(res)
async def synctime(): consul = ConsulBackend() resp, text = await consul.get_nodes_for_service("home", ['rtc']) if resp.status != 200: log.error("Error loading rtc nodes") return msg = json.loads(text) hosts = [f"http://{h['Address']}:{h['ServicePort']}/time" for h in msg] response = await asyncio.gather(*[config.get(h) for h in hosts]) times = [] for r, text in response: assert r.status == 200 times.append(float(text)) min_time, max_time = min(times), max(times) delta = max_time - min_time if delta > 60.0: log.error("RTC time difference too great") return t = max_time if abs(time.time() - t) > 60.0: log.info("Adjusting clock") time.clock_settime(time.CLOCK_REALTIME, t) else: log.info("No need to adjust time")
def test_clock_settime(self): t = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, t) except PermissionError: pass if hasattr(time, "CLOCK_MONOTONIC"): self.assertRaises(OSError, time.clock_settime, time.CLOCK_MONOTONIC, 0)
def test_clock_settime(self): t = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, t) except PermissionError: pass if hasattr(time, 'CLOCK_MONOTONIC'): self.assertRaises(OSError, time.clock_settime, time.CLOCK_MONOTONIC, 0)
def test_monotonic_settime(self): t1 = time.monotonic() realtime = time.clock_gettime(time.CLOCK_REALTIME) try: time.clock_settime(time.CLOCK_REALTIME, realtime - 3600) except PermissionError as err: self.skipTest(err) t2 = time.monotonic() time.clock_settime(time.CLOCK_REALTIME, realtime) self.assertGreaterEqual(t2, t1)
def test_monotonic_settime(self): t1 = time.monotonic() realtime = time.clock_gettime(time.CLOCK_REALTIME) # jump backward with an offset of 1 hour try: time.clock_settime(time.CLOCK_REALTIME, realtime - 3600) except PermissionError as err: self.skipTest(err) t2 = time.monotonic() time.clock_settime(time.CLOCK_REALTIME, realtime) # monotonic must not be affected by system clock updates self.assertGreaterEqual(t2, t1)
def cmd_0x21(self, argument: bytes): # set time newtime = int.from_bytes(argument[1:], "big") print("Previous Time:\t {}".format( strftime("%Y-%m-%d %H:%M:%S", gmtime()))) time.clock_settime(time.CLOCK_REALTIME, newtime) print("New Time: \t {} ({})".format( datetime.utcfromtimestamp(newtime).strftime("%Y-%m-%d %H:%M:%S"), newtime, ss, )) return ErrorCode.Ok
def setSystemTime(self, t): """Set system time from gps time """ print(t) # Convert to full datetime now = dt.datetime.now() d = dt.datetime.combine(dt.date(now.year, now.month, now.day), t) # Convert to seconds seconds = (d - dt.datetime(1970, 1, 1)).total_seconds() # set clock time.clock_settime(time.CLOCK_REALTIME, seconds) print('Clock set')
def main(argv): """ Entry point for ntpclient.py. Arguments: argv: command line arguments """ res = None quiet = False args = set(argv) if {'-q', '--quiet'}.intersection(args): quiet = True if '-s' in argv: server = argv[argv.index('-s') + 1] elif '--server' in argv: server = argv[argv.index('--server') + 1] elif 'NTPSERVER' in os.environ: server = os.environ['NTPSERVER'] else: server = 'pool.ntp.org' if {'-h', '--help'}.intersection(args): print( 'Usage: ntpclient [-h|--help] [-q|--quiet] [-s|--server timeserver]' ) print(f'Using time server {server}.') sys.exit(0) t1 = time.clock_gettime(time.CLOCK_REALTIME) ntptime = get_ntp_time(server) t4 = time.clock_gettime(time.CLOCK_REALTIME) # It is not guaranteed that the NTP time is *exactly* in the middle of both # local times. But it is a reasonable simplification. roundtrip = round(t4 - t1, 4) localtime = (t1 + t4) / 2 diff = localtime - ntptime if os.geteuid() == 0: time.clock_settime(time.CLOCK_REALTIME, ntptime) res = 'Time set to NTP time.' localtime = datetime.fromtimestamp(localtime) ntptime = datetime.fromtimestamp(ntptime) if not quiet: print('Using server {}.'.format(server)) print('NTP call took approximately', roundtrip, 's.') print('Local time value:', localtime.strftime('%a %b %d %H:%M:%S.%f %Y.')) print('NTP time value:', ntptime.strftime('%a %b %d %H:%M:%S.%f %Y.'), '±', roundtrip / 2, 's.') print('Local time - ntp time: {:.6f} s.'.format(diff)) if res: print(res)
def recover(self): self.is_active = False if self.faulting_thread != None: self.faulting_thread.join() self.faulting_thread = None if path.exists(self.storage): normal_offset = 0 with open(self.storage, 'r') as storage: normal_offset = json.load(storage)["normal_offset"] time.clock_settime( time.CLOCK_REALTIME, time.clock_gettime(time.CLOCK_MONOTONIC) + normal_offset) os.remove(self.storage) self.is_injected = False return {"status": "ok"}
def force_sync_time(unix_time): """Set the raspberry time to the unix time given as parameter. Arguments: unix_time {str} -- The unix time to set the raspberry pi to. Unix time is given in seconds since January 1, 1970. Returns: bool -- Returns false if the time was unable to be set. """ try: clk_id = time.CLOCK_REALTIME time.clock_settime(clk_id, float(unix_time)) except Exception as e: print("Unable to set clock time.") print(e) error_handler()
def main(argv): """ Entry point for ntpclient.py. Arguments: argv: command line arguments """ res = None quiet = False args = set(argv) if {'-q', '--quiet'}.intersection(args): quiet = True if '-s' in argv: server = argv[argv.index('-s')+1] elif '--server' in argv: server = argv[argv.index('--server')+1] elif 'NTPSERVER' in os.environ: server = os.environ['NTPSERVER'] else: server = 'pool.ntp.org' if {'-h', '--help'}.intersection(args): print('Usage: ntpclient [-h|--help] [-q|--quiet] [-s|--server timeserver]') print(f'Using time server {server}.') sys.exit(0) t1 = time.clock_gettime(time.CLOCK_REALTIME) ntptime = get_ntp_time(server) t4 = time.clock_gettime(time.CLOCK_REALTIME) # It is not guaranteed that the NTP time is *exactly* in the middle of both # local times. But it is a reasonable simplification. roundtrip = round(t4 - t1, 4) localtime = (t1 + t4) / 2 diff = localtime - ntptime if os.geteuid() == 0: time.clock_settime(time.CLOCK_REALTIME, ntptime) res = 'Time set to NTP time.' localtime = datetime.fromtimestamp(localtime) ntptime = datetime.fromtimestamp(ntptime) if not quiet: print('Using server {}.'.format(server)) print('NTP call took approximately', roundtrip, 's.') print('Local time value:', localtime.strftime('%a %b %d %H:%M:%S.%f %Y.')) print('NTP time value:', ntptime.strftime('%a %b %d %H:%M:%S.%f %Y.'), '±', roundtrip/2, 's.') print('Local time - ntp time: {:.6f} s.'.format(diff)) if res: print(res)
def keep_faulting(self, period_ms): strobe_log.info("keep_faulting") try: wierd = False while self.is_active: to = time.clock_gettime(time.CLOCK_MONOTONIC) + ( self.wierd_offset if wierd else self.normal_offset) strobe_log.info("setting time to: " + str(to)) time.clock_settime(time.CLOCK_REALTIME, to) strobe_log.info("setting time to: " + str(to)) wierd = not wierd time.sleep(float(period_ms) / 1000) except: e, v = sys.exc_info()[:2] print("Run into an unexpected error " + str(e) + ": " + str(v) + " @ " + traceback.format_exc()) raise
def on_loop(self): if self._state == States.OFF: return try: data = self._skytraq.read() except SkyTrackError as exc: logger.error(exc) return if data[NavData.FIX_MODE.value] == FixMode.NO_FIX: self.data_rec[1].value = 0 else: # datetime from gps message dt = gps_datetime(data[NavData.GPS_WEEK.value], data[NavData.TOW.value]) # sync clock if it hasn't been syncd yet if self.sync_enable_obj.value and not self.is_syncd_obj.value: clock_settime(CLOCK_REALTIME, dt) logger.info('set time based off of skytraq time') self.is_syncd_obj.value = True # add all skytraq data to OD for i in range(1, len(data)): self.data_rec[i].value = data[i] self.data_rec[0x14].value = scet_int_from_time(int(dt)) # send gps tpdos self.send_tpdo(2) self.send_tpdo(3) self.send_tpdo(4) self.send_tpdo(5) # update status if data[NavData.NUMBER_OF_SV.value] >= 4 and \ data[NavData.FIX_MODE.value] >= FixMode.FIX_2D: self._state = States.LOCKED else: self._state = States.SEARCHING
def adjClock(self, delta=None): if delta is None: delta = self.last_delta if delta is None: print('No delta provided or stored, so time not set') return None old_sys_epoch = time.time() new_sys_epoch = old_sys_epoch + delta old_t = datetime.datetime.fromtimestamp(old_sys_epoch) new_t = datetime.datetime.fromtimestamp(new_sys_epoch) print("Adjustment delta: {0}".format(delta)) print("Old sys time: {0}, ts: {1}".format(str(old_t), old_sys_epoch)) print("New sys time: {0}, ts: {1}".format(str(new_t), new_sys_epoch)) try: time.clock_settime(time.CLOCK_REALTIME, new_sys_epoch) print('System clock set.') return new_t except Exception as e: print('Could not set system clock, probably a permissions thing.') return None
def set_system_time(time): clock_settime(0, float(time))
SCRIPT.call("setGenre", track['persistent_id'], track['genre']) for track in master_changes: # TODO: Make sure we handle missing values properly if track['date_added_secs'] is not None: if track_cloud_status != "cloud": # If local file, delete and re-add path = SCRIPT.call('getFilePath', track['persistent_id']) new_path = '/Users/AB/Desktop/itunesutils_tmp/' copy(path, new_path) metadata = get_metadata(track['persistent_id']) playlists = SCRIPT.call('getPlaylists', track['persistent_id']) # TODO: does deleting it this way remove the file from iTunes media? # TODO: Do I need to purge the itunesutils_tmp folder? SCRIPT.call('deleteTrack', track['persistent_id']) time.clock_settime(time.CLOCK_REALTIME, track['date_added_secs']) new_pid = SCRIPT.call('addFile', new_path) # Transfer all metadata from the file just deleted to the new one if metadata.get('genre'): SCRIPT.call("setGenre", new_pid, metadata.get('genre')) if metadata.get('played_count'): SCRIPT.call("setPlaycount", new_pid, metadata.get('played_count')) if metadata.get('skipped_count'): SCRIPT.call("setSkipcount", new_pid, metadata.get('skipped_count')) if metadata.get('rating'): SCRIPT.call("setRating", new_pid, metadata.get('rating')) if metadata.get('loved'): SCRIPT.call("setLoved", new_pid, metadata.get('loved')) if len(playlists) != 0: SCRIPT.call("addToPlaylists", new_pid, playlists)
# Calculate the median of all received times. # Since median() can not really handle datetime objects, we convert them # to UNIX timestamps and convert the result back to datetime, this time # adding timezone information. new_time = (datetime.fromtimestamp(median([t.timestamp() for t in times ])).replace(tzinfo=timezone.utc)) now = datetime.now(tz=timezone.utc) adjustment = new_time - now interval = times[-1] - times[0] # Check if the new time is close enough to the current time. if args.max_adjust and args.max_adjust < abs(adjustment.total_seconds()): print('Error: Offset between local and remote clock is {:.2f} seconds. ' 'Only {} seconds are allowed.'.format(adjustment.total_seconds(), args.max_adjust)) sys.exit(E_LARGEOFFSET) if not args.quiet: # Display a short summary about how much the time changes and # how much the remote clocks agree. print('Time adjustment: {:.2f} seconds'.format(adjustment.total_seconds())) print('{} remote clocks returned usable time information, {} did not.'. format(succeeded, failed)) if succeeded > 1: print('Remote clocks deviate by {}'.format(interval)) if not args.dry_run: # Actually set the system clock to the new time. time.clock_settime(time.CLOCK_REALTIME, new_time.timestamp())
def set_system_clock(self, **kwargs): # Needs validation (talk to Viraj) # need to validate this works, and need to integrate updating RTC unix_epoch = kwargs['epoch'] clk_id = time.CLOCK_REALTIME time.clock_settime(clk_id, float(unix_epoch))
from turtle import * import webbrowser import time import datetime time.clock_settime(m, 20) i = 0 if m >= 20 and m <= 21: time.sleep(30) color('red', 'white') begin_fill() while i < 5: circle(50) right(60) circle(50) i = i + 1 webbrowser.open("youtube.com") elif m > 21 and m <= 22: time.sleep(30) color('yellow', 'white') begin_fill() while i < 24: circle(100) right(15) circle(100) i = i + 1 webbrowser.open("google.com")