DEV Community

Cover image for Automatically Setting Your Computer's time with Python
Lucretius Biah
Lucretius Biah

Posted on • Edited on • Originally published at kudadam.com

Automatically Setting Your Computer's time with Python

A few months ago, when the CMOS battery inside my computer died, I was having a problem with my PC's time.
I had to set it on each boot and it was very boring so I decided to make a python script to automate the whole process

How it Works?

So, here's how the script works,
On every reboot:

  • The script makes a call to an API to get the current time based on my I.P address,
    If my computer is not connected to the internet, it sleeps and check again in five minutes time πŸ†’

  • It then sets the time using the value it got from the API

Writing the code

So, we are going to write the code used to generate the program.
Open your IDE and create a new python file and name it whatever you want and let's start coding

import requests #Module for handing the request to the API
from time import sleep #The sleep is used to make the program wait if there is no internet connection
import json #For parsing the JSON response from the server
import re # Regex for extracting the current time
from subprocess import Popen

def set_current_time():
  """Function to return the current time"""
  try:
    res = requests.get("http://worldtimeapi.org/api/ip")
    data = res.text
    time_regex = r"\d+:\d+:\d+"
    datetime =  json.loads(data)['datetime'];
    date = re.search(time_regex,datetime).group()
    Popen(['time',date],shell = True)
  except requests.exceptions.ConnectionError:
    #This code is executed incase there is a connection error.
    sleep(3000)

set_current_time()

Enter fullscreen mode Exit fullscreen mode

So, that's the code for the program.
We get the datetime and extract the time using a regular expression. Then we use the subprocess module to run a shell command which then set's the time.
If the request is made to the API and there is no internet connection, it will wait for 3000 seconds (5 minutes) before making another request to the server.

When you are done, save this file with a .pyw extension instead of .py, this will prevent the application from lauching the console when it is running.
Finally, place this file inside %appdata%/Microsoft/Windows/Start Menu/Startup.
Restart your computer and see the magic.

Top comments (0)