Home > Blockchain >  Python script to reset date and time
Python script to reset date and time

Time:11-24

Some time ago, this post appeared asking how to use Python to change system date and time. The answer by Amir on that post worked for me, and I'm able to use his same script to change my computers date and time as displayed on the bottom-right of my screen to whatever I want it to. However, I'm now trying to create a second, slightly modified script to reset date and time to what it should be in real time. So the idea is, I can execute one script and then change my system date and time. Then, I execute a second script and reset the system date and time to what it "should be", in real time, as it was before I ran the first script. I've not been able to figure it out so far though. In Amir's script, the following code was used;

time_tuple = (2012,  # Year
              9,  # Month
              6,  # Day
              0,  # Hour
              38,  # Minute
              0,  # Second
              0,  # Millisecond
              )

I thought I'd be able to make this work by simply making the following modification;

import time
time_tuple = time.gmtime()[0:7]

The <time.gmtime()[0:7]> hypothetically has a tuple which contains the real, present-time at the moment. And I used [0:7] to match the seven values in the original tuple. But when I run this code, it does not reset my computers system date and time to real-time. (It doesn't help when I remove the [0:7].) Does anyone know something that will work here?

CodePudding user response:

Thanks a lot to the info by @Greg Hewgill. I was able to solve my problem above using the following, if anyone was interested. I got the API information from http://worldtimeapi.org/. The tuple code I built was;

import requests
timeapi = requests.get("http://worldtimeapi.org/api/timezone/Etc/GMT")
tuple_info = timeapi.json()['datetime']
year = int(tuple_info[0:4])
month = int(tuple_info[5:7])
day = int(tuple_info[8:10])
hour = int(tuple_info[11:13])
minute = int(tuple_info[14:16])
second= int(tuple_info[17:19])
millisecond = 0
api_tuple = (year,month,day,hour,minute,second,millisecond)

CodePudding user response:

After changing your system time, your computer only knows the new time. It does not "remember" the original time, so that's why time.gmtime() also returned the new time.

To have your computer learn what the real world time is again, the input has to come from somewhere outside your computer. You can either type in the current time manually, or you could write a script to call some time API service. I found several freely available ones by searching for "time api".

  • Related