Skip to content
Navigation Menu
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Update time on Windows with IIT Bombay NTP server
The following blog post discusses two solutions to updating time through an external/local NTP server on a Windows machine.
Problem
Windows would not update time using the standard NTP servers since they are blocked on the network.
The system time often gets messed up when switching between different operating systems on a multi-boot machine (solution to this specific problem in appendix). This problem arises when you are on a network (like the IIT Bombay network) that blocks outside NTP servers. IIT Bombay has its own NTP server- ntp.iitb.ac.in. All other standard NTP servers (like time.windows.com, time.nist.gov, pool.ntp.org) are blocked.
This problem can be easily solved on linux machines by simply adding the NTP server to /etc/ntp.conf. However, in Windows, the control panel settings would not allow you to add an external NTP server (in our case ntp.iitb.ac.in).
Trying to force an update through a pre-defined NTP server (like time.nist.gov) results in a time out, as shown-
Checking if an NTP server is accessible-
On windows you can check if an NTP server is accessible by running the following command in command prompt-
w32tm /stripchart /computer:ntp.iitb.ac.in /dataonly /samples:3
(Replace ntp.iitb.ac.in with your NTP server address)
This command is analogous to running ntpdate -q ntp.iitb.ac.in on a linux machine.
Testing the above command on IIT-B network, reveals this-
time.nist.gov is inaccessible while ntp.iitb.ac.in is accessible.
Solution 1: Python Script with Windows Task Scheduler
Description:
Make a list of NTP servers, and send a request to each until a response is received. Use socket to send a request to the NTP server on port 123. (Reference: Simon Foster’s recipe). Use win32api to update system time.
Step 1: Install Dependencies
All dependencies are standard libraries apart from win32api (a.k.a. pywin32).
Install pywin32 from here or simply do a pip install pywin32.
To install pip for Windows, refer this.
Step 2: Download the script
The script can be found in this gist.
Find Raw file here.
This script is tested with Python 2 and 3.
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'
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)
Download the file and save it at a location you’ll remember.
For the purpose of this demonstration, I’ll be saving it inside- C:\Python27\ntp_update_time.py with my Python installation directory as C:\Python27.
Step 3: Test the script
Open Command Prompt with admin privileges- Hit key combo Windows + X, and click on Command Prompt (Admin).
Type:
cd C:\Python27
python ntp_update_time.py
If you were on IIT-B network and everything worked well, it should say- Time updated to: 2018-03-30 19:04 from ntp.iitb.ac.in
Step 4: Schedule a Task
Similar to a cronjob in Unix, you can create a task to run periodically using Windows Task Scheduler.
-
Search for “Task Scheduler” from the start menu and open it.
-
Create a basic task from the Actions menu at the right
- Under the General tab, give a name and description to the task. Check the “Run with highest privileges” checkbox.
- Under the Triggers tab, click on New, and set “Begin the task:” to “On workstation unlock”. Leave everything as is, and hit Ok.
- Under the Actions tab, set Program/Script to your python path (
C:\Python27\python.exe) and set “Add arguments (optional)” to the script path (C:\Python27\ntp_update_time.py).
- Under the Conditions tab, uncheck the checkbox under Power which says “Start the task only if the computer is on AC power”.
- Hit Ok and save the Task. Return to the Task Scheduler window, double click on “Task Scheduler Library” on the left navigation drawer. Select the task you made from the list and click on it. Hit “Run” from the right hand actions menu. (Make sure to screw up your system time before running. If it gets fixed after you run the task, everything is set up to work.)
The task would be scheduled to run every time you unlock your machine. This makes sense since mostly the time gets messed up when switching between two different Operating Systems on a multi-boot machine.
This solution uses the Windows Time Service tool to add an external/local NTP server.
- Open Command Prompt with admin privileges- Hit key combo
Windows+X, and click onCommand Prompt (Admin). - Stop the time service-
net stop w32time - Type in
w32tm /config /syncfromflags:manual /manualpeerlist:"ntp.iitb.ac.in,pool.ntp.org"to manually set the list of external/local NTP servers. - Force set the connection as reliable-
w32tm /config /reliable:yes - Start the time service-
net start w32time - Check if the configuration has been written successfully-
w32tm /query /configurationandw32tm /query /status. You should see “NtpServer: ntp.iitb.ac.in,pool.ntp.org (Local)”. - Do a
w32tm /resyncto force an update. (Make sure your system time is messed up to see if it gets corrected).
Solution 3: No NTP server reachable, update using HTTPS
In case you are unable to reach any NTP server, you can use the following script to update the time by scraping duration since epoch time from www.unixtimestamp.com.
The script can be found in this gist.
Find Raw file here.
import requests
import datetime
import win32api
page = requests.get('https://www.unixtimestamp.com/', headers={'Cache-Control': 'no-cache'})
text = page.text
for line in text.split("\n"):
match_text = "<h3 class=\"text-danger\">"
suffix = " <small>seconds since Jan 01 1970. (UTC)</small></h3>"
if match_text in line:
line = line.replace('<',' ').replace('>',' ')
epoch_time = [int(s) for s in line.split() if s.isdigit()][0]
break
utcTime = datetime.datetime.utcfromtimestamp(epoch_time)
try:
# SetSystemTime takes time as argument in UTC time
win32api.SetSystemTime(utcTime.year, utcTime.month, utcTime.weekday(), utcTime.day, utcTime.hour, utcTime.minute, utcTime.second, 0)
localTime = datetime.datetime.fromtimestamp(epoch_time)
print("Time updated to: " + localTime.strftime("%Y-%m-%d %H:%M"))
except:
print("Could not update time")
- Install requests-
pip install requests.
To install pip for Windows, refer this. - Follow Step 3 and Step 4 from Solution 1, using the script above.
Appendix
Specifically pertaining to the problem of the system time going haywire when dual booting across Windows and Linux, the Official Ubuntu documentation explains what causes this.
In essence, Linux/Unix systems store UTC as the time on the hardware clock and with good reason, since this saves unnecessary changes to the hardware clock when moving between timezones. On the other hand, Windows stores the local time as the time on the hardware clock. This ends up messing with the system time since both OS deal with the hardware clock differently.
The Official Ubuntu Docs list down a step by step solution to avoid this from happening.
That should save you from manually setting time again.
Till next ‘time’..
Cheers!
Python is a versatile and widely used programming language, known for its simplicity and easy-to-understand syntax. When you’re setting up a Python development environment, one of the first tasks is locating where Python is installed on your machine. This information is crucial for configuring different tools and managing libraries and environments.
Python is normally installed in the system’s default program files directory. On Windows, it’s typically found in the “C:\PythonXX” folder. On Linux or Mac, it’s often in “/usr/local/bin/pythonX.X”. You can check your Python installation path by running “python –version” or “which python” in the command line.
This article will help you understand how to find the Python installation location on your system, focusing on different methods and operating systems. This knowledge will assist you in setting up your programming environment correctly and provide a better understanding of how Python interacts with your machine.
Let’s get into it!
Python Installation Locations
On various operating systems like Windows, macOS, or Linux, Python’s installation location can vary due to user preferences or installation packages from different sources.
In this section, we’ll look at the installation location of Python for different operating systems. Specifically, we’ll look at the following:
- Python Installation location on Windows
- Python Installation location on MacOS
- Python Installation location on Linux
1. Python Installation Location on Windows
By default, Python installations on Windows are located in the C:\ directory or C:\Users\<User>\AppData\Local\Programs.
The common installation paths for both 32-bit and 64-bit versions may reside in the C:\PythonXX folder, where XX stands for the Python version (e.g., C:\Python27 for Python 2.7).
In newer installations, the 64-bit version is often located in the C:\Program Files\PythonXX folder, while the 32-bit version is in the C:\Program Files (x86)\PythonXX folder.
To find the exact location of your Python installation on Windows, you can use the command prompt by typing where python and press Enter. This command will display the file paths of any installed Python versions on your system.
The following image demonstrates this prompt:
2. Python Installation Location on MacOS
On macOS, Python is typically installed in the /Library/Frameworks/Python.framework/Versions directory, with different versions contained in their respective subfolders (e.g., /Library/Frameworks/Python.framework/Versions/3.9 for Python 3.9).
Alternatively, Python installations managed by Homebrew are located in /usr/local/Cellar/python.
To check the exact path of your Python installation, you can open the terminal and type which python or which python3. Pressing “Enter” will display the file path of the active Python version on your system.
3. Python Installation Location on Linux
In most Linux distributions, Python is installed by default and can be found in the /usr/bin/ directory. The installed versions usually include both Python 2 and Python 3.
For Python 2.x, the executable is named python, while for Python 3.x, it’s named python3.
For systems with multiple Python installations or custom installation paths, you can find the location by typing which python or which python3 in the terminal and pressing Enter.
The command will show the file path of the active Python version on your system.
In the next section, we’ll go over how you can use built-in Python modules to locate the Python folder in your system.
How to Use Python’s os and sys Modules to Locate Python Folder
Python’s os and sys modules are built-in modules that allow you to interact with the operating system.
To locate where Python is installed, follow the steps given below:
- Run Python interpreter by typing python in the terminal or command prompt.
- Execute the following commands:
import os
import sys
print(os.path.dirname(sys.executable))
This Python script is used to print the directory of the Python interpreter being used to execute the script. os.path.dirname(sys.executable) gets the path of the currently running Python interpreter.
The output is given below:
How to Check the Location of Python Executables
When you are working in Python, you’ll want to install libraries from time to time. In most cases, you might want to check the path of a certain library.
You can check the path of a Python library or executable with the pip package manager. To do this, open up CMD and run the following code:
pip show <package name>
Let’s say I want to check the location of NumPy library on my operating system. To do this, I’ll type the following prompt in CMD:
pip show numpy
The output is given below:
How to Configure Python Path
When you first install Python on Windows, it’s important that you configure the path environment variable.
This means you should let your operating system know the path of your installation folder, which will allow the interpreter to refer to this path when running Python files.
We’ve listed a step-by-step guide to setting your environment variable and variables below:
Windows
- Right-click on ‘My Computer’ or ‘This PC,’ and select ‘Properties.’
- Click on ‘Advanced system settings.’
- Go to the ‘Advanced’ tab and click on ‘Environment Variables.’
- In the ‘System variables’ section, locate the ‘Path’ variable, select it, and click on ‘Edit.’
- Add the path to the Python executable (e.g., C:\Python<version>\Scripts;C:\Python<version>), and click ‘OK.’
macOS and Linux
- Open the terminal (Terminal on macOS, and Ctrl + Alt + T on Linux).
- Edit the shell configuration file (~/.bashrc for bash shell, ~/.zshrc for zsh shell).
- Add the following line: export PATH=”/path/to/python-<version>/bin:$PATH”
- Save the file and restart the terminal for the changes to take effect.
How to Verify Python Version and Installation
Before starting any Python project, it’s essential to know the version of Python installed on the system as well as its location.
It’ll help you ensure compatibility between packages, libraries, and other tools.
This section will guide you through verifying your Python version and installation using various Python-related commands and performing cross-platform checks.
1. Python-related Commands
To find the version of Python installed on any platform, you can use the python –version command in the terminal or command prompt.
It returns the Python 2 version installed on your system. To check for the Python 3 version, you can use the python3 –version command instead. These commands help you determine which Python interpreter you are currently using.
In case you are using both Python 2 and Python 3 versions, you can verify the compatibility of a specific module by importing it into the Python interpreter.
For example, to check if the re module is compatible, you can try running the following command:
import re
print(re.__version__)
When you run the above command, you’ll get an output similar to the following:
An output like the above suggests that Python’s re module is compatible with your current Python version.
If you’d like to learn how to switch to the latest version of Python, check out our quick and easy guide on how to update Python.
2. Cross-platform Verification
To find where Python is installed on your system, you can use the following Python code snippet for a cross-platform solution:
import sys
print(sys.executable)
This code will print the location of the Python interpreter executable. Depending on your operating system, this might differ.
The output is given below:
By knowing this location, you can ensure that you are using the correct Python interpreter for your projects.
Troubleshooting Common Python Issues
In this section, we’ll talk about some common issues that you may face when working with Python paths.
Let’s get into it!
1. Path-related Problems
For beginners, one common problem when using Python is related to file paths.
When Python is installed, its location may not be added automatically to the system environment variables PATH.
This could result in the “Python not found” error when trying to run Python scripts or access the Python shell.
To troubleshoot this issue, you can:
- Ensure Python is installed correctly by checking the installation folder, typically found in:
- Windows: C:\Python{version}
- macOS and Linux: /usr/local/bin/python{version}
- Add Python to the PATH variable to make it accessible system-wide:
- Windows: Open the Control Panel, navigate to System and Security > System > Advanced system settings > System Environment Variables, and edit the PATH variable to include the Python installation folder.
- macOS and Linux: Open the terminal and add the Python installation directory to the PATH variable using the export command, such as export PATH=/usr/local/bin/python{version}:$PATH.
- Save and restart the terminal or Command Prompt to apply the changes.
After following the steps above correctly, you’ll no longer run into any errors with running Python files.
2. Version Compatibility
Different Python versions might lead to version compatibility issues, especially when working with third-party modules and libraries.
To overcome this, you can:
- Check your Python version by running python –version in the terminal or Command Prompt.
- Verify the compatibility of a package by checking its documentation or the PyPI page. Packages usually list compatible Python versions.
- Use a virtual environment to manage and isolate dependencies for different projects.
By addressing path-related problems and ensuring version compatibility, you can resolve some of the most common Python issues.
To learn more about error resolution in Python, check the following video out:
Final Thoughts
Understanding where Python is installed on your system is a fundamental aspect of becoming an efficient programmer.
It allows you to manage your programming environment effectively and is key when dealing with using multiple versions of Python versions or when installing modules.
It also helps you in cases when you want to use specific versions for different projects, or when you need to install packages globally or just for one project.
Furthermore, knowing the path of your Python installation can also help you troubleshoot issues related to your environment setup or version conflicts and fine-tune your coding environment to your liking.
It’s an essential step in setting up an integrated development environment, and it makes using code editors or Python-related software smoother and more efficient!
Frequently Asked Questions
In this section, we’ve listed some frequently asked questions that most beginners have related to the Python installation directory.
Where is Python install location on Windows?
Python is installed in the default location C:\PythonXY where XY represents the version number.
For example, C:\Python39 for Python 3.9. It might also get installed under C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.
How to find Python location in CMD?
To find the Python installation path in CMD, you can use the following command:
python -c
import os, sys
print(os.path.dirname(sys.executable))
This command imports the os and sys modules and prints the directory of the Python executable.
Where is Python’s location in Windows 10?
On Windows 10, Python’s default location is C:\PythonXY or C:\Users\YourUsername\AppData\Local\Programs\Python\PythonXY for per-user installations.
How to check if Python is installed?
To check if Python is installed, open a command prompt or terminal and type in:
python --version
If Python is installed, the command will display the version of Python.
If it’s not installed, you’ll get an error or the Microsoft Store may open for Python installations in certain cases on Windows.
How to find Python package’s installation location?
Python packages are generally installed in a subfolder of the Python installation. The specific location depends on whether you’re using a virtual environment or not.
To find the installation location of a package, open a terminal or command prompt and type:
pip show package-name
Replace “package-name” with the name of the package you want to find the location for. The output will show the package’s location along with other information.
Maintaining accurate time on your server is critical largely because many services and IT applications rely on accurate time settings to function as expected. These include logging services, monitoring and auditing applications, and database replication to mention a few.
Time skew in servers, and any client systems for that matter, is undesirable and usually causes conflict in time-critical applications. To maintain accurate time settings on your server and across the network by extension, it’s preferred to install and enable a NTP server on your server.
What is an NTP server?
NTP, short for Network Time Protocol, is a protocol that synchronizes time across network devices. It listens on UDP port 123 and always ensures that time inconsistencies across the server and client systems are mitigated and that client systems are always in sync with the server.
NTP server refers to a network device or a service that fetches time from an external time source and syncs the time across the network using the NTP protocol. This guide will focus on installing NTP service on Windows server 2019.
How Does NTP Work ?
Being a protocol, NTP requires a client-server architecture. The NTP client residing on a Windows PC, for example, initiates a time request exchange with the NTP server.
A time-stamp data exchange happens between the server and client and this helps in adjusting the clock on client’s systems to the highest degree of accuracy to match the time on the NTP server. In this guide, we will walk you through the installation and configuration of NTP server on Windows Server 2019.
There are several ways of setting up NTP server and we will look at each in turn.
In Windows Server environments, there is a special Windows time service that handles time synchronization between the server and the client systems. This is known as Windows Time service. PowerShell provides a command-line tool known as w32tm.exe and comes included in all versions of Windows from Windows XP and Windows Server 2008 to the latest versions of each OS.
Using the w32tm.exe utility, you can configure your Windows system to sync with online time servers. Usually, this is the tool of choice when setting up and monitoring time on your Windows Server system.
Using the command-line utility is quite straightforward.
For example, to set the Server to point to 2 different time servers, namely 0.us.pool.ntp.org and 1.us.pool.ntp.org , launch PowerShell as the Administrator and run the command below
w32tm /config /syncfromflags:manual /manualpeerlist:”0.us.pool.ntp.org 1.us.pool.ntp.org” /update
Then restart Windows Time service using the commands:
Stop-Service w32time
Start-Service w32time
Here’s a snippet of the commands.
You can thereafter confirm the values of NTP servers configured in the registry by running this command:
w32tm /dumpreg /subkey:parameters
Configure NTP Server on Windows Server 2019 using Registry editor
The second method of installing and configuring the NTP server is using the registry editor. If you are not a fan of the Windows PowerShell, then this will truly come in handy.
To get started, open the registry editor. Press ‘Windows key + R’ and type ‘regedit’ and hit ENTER. The windows registry will be launched as shown below.
Next, head over to the path shown below
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer
On the right pane. Be sure to find & double-click the file labelled ‘Enabled’ in the diagram shown below.
Next, In the ‘value data’ text field, set the value to ‘1’ and click the ‘Ok’ button.
Next, head over to the path:
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\Config
In the right pane, double click the ‘Announce Flags’ file.
Double-click the file and in the Value data text field, type the value ‘5’ and click ‘OK’.
For the changes to come into effect, you need to reboot the NTP server by heading to the services Window. To achieve this, press ‘Windows key + R’ and type ‘services.msc’. Scroll and find ‘Windows Time’, right-click on it and select the ‘Restart’ option.
Useful w32tm commands
Once you have set up your NTP server, you can use the following commands to verify various aspects of the server:
To check the status of the NTP server, run the command:
w32tm /query /status
To reveal the current NTP pool being used to sync time with execute:
w32tm /query /source
You can also display a list of NTP time servers along with their configuration status as shown.
w32tm /query /peers
To display NTP server configuration settings, run the command:
w32tm /query /source
This shows quite a wealth of information.
Final Take
We cannot stress enough how important it is to maintain accurate time and date settings on your server. As you have seen, setting up an NTP server on your Windows server instance is quite easy and straight forward.
Once you have configured the NTP service on your server, other domain controllers in your environment will sync with this server and the Windows clients in the domain will sync with the domain controllers. Hopefully, you can now install and configure NTP on Windows Server 2019.
Python windows system time synchronization
#!/usr/bin/env python
# coding: utf8
# Usage: Specify the ntpserver domain name to the ntpserver_domains variable.
import socket
import struct
import time
import win32api
import subprocess
import os
import sys
def gettime(ntpserver_ips):
TIME_1970 = 2208988800L
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.settimeout(3)
data = '\x1b' + 47 * '\0'
Port=123
for server in ntpserver_ips:
success = False
count = 1
'''Every ip try 3 times''
while not success and count < 4:
try:
client.sendto(data, (server, Port))
data = client.recvfrom(1024)[0]
success = True
print server+' get time success, tried '+str(count)+' times.'
except socket.timeout:
print server+' get time failed, tried '+str(count)+' times.'
count += 1
if success == True:
break
data_result = struct.unpack('!12I', data)[10]
data_result -= TIME_1970
return data_result
def settime(nowtime):
tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst = time.gmtime(nowtime)
win32api.SetSystemTime(tm_year, tm_mon, tm_wday, tm_mday, tm_hour, tm_min, tm_sec, 0)
print u'Set system time success.'
def getip_with_domains(ntpserver_domains):
ips = []
for i in ntpserver_domains:
ip = socket.gethostbyname_ex(i)[2]
ips.extend(ip)
return ips
if __name__ == '__main__':
ntpserver_domains = ['cn.pool.ntp.org', 'ntp.sjtu.edu.cn', 'time.windows.com']
ntpserver_ips = getip_with_domains(ntpserver_domains)
if not ntpserver_ips or len(ntpserver_ips) != len(set(ntpserver_ips)):
print u'Some domain can not resolve ip.'
print os.system('pause')
sys.exit()
else:
nowtime = gettime(ntpserver_ips)
settime(nowtime)
print u'Now Time:',time.strftime('%Y-%m-%d %X')
os.system('pause')
Reprinted at: https://blog.51cto.com/sndapk/1830038
Intelligent Recommendation
Time synchronization under windows
Window 2008 LAN setting time server (time synchronization server) In a LAN, only one server can connect to the Internet, and other servers must ensure that the server time is consistent. By…
More Recommendation
Windows time synchronization script
1, write scripts Note: There is no self-installation of modules such as NTPLIB, and the installation process: 1、Terminal — pip install ntplib 2, become an executable script 1. Open Pycharm. 2, open …
Liunx system time synchronization
There is a problem after the liunx server is adjusted. You can only use the crontab timing synchronization time of liunx: First adjust the current system time and write to the liunx kern…
Linux system time synchronization
Beijing Get Interface: suning Interface:http://quan.suning.com/getSysTime.do Taobao Interface: Linux system time: ntpd time synchronization system: Synchronization time zone, copy the file system of u…
