Many programs rely on the accurate machine time, such as the make command in UNIX. Your machine time may be different and need synchronizing with another time server in your network.
Printing the current time from the internet time server
Getting ready
In order to synchronize your machine time with one of the internet time servers, you can write a Python client for that. For this, ntplib will be used. Here, the client/server conversation will be done using Network Time Protocol (NTP). If ntplib is not installed on your machine, you can get it from PyPI with the following command using pip or easy_install:
$ pip install ntplib
If pip is not installed on your computer, first install it before executing the preceding command. In Debian-based Linux distributions such as Ubuntu, this can be installed by:
$ sudo apt install python-pip
Note that you will need to install pip for Python 3 separately if you are running it along side Python 2, as typically Python 2 is set as the default version:
$ sudo apt-get install python3-pip
Similarly, ntplib needs to be installed for python3-pip (also called pip3) separately:
$ pip3 install ntplib
It is a good idea to upgrade pip to the latest version if you are running an outdated version, by issuing the following command:
$ pip install --upgrade pip
or:
$ pip3 install --upgrade pip
If Python 2 and Python 3 are installed alongside in your computer then use pip3.
I am using the pip version 9.0.1, for both Python 2 and Python 3. This is the latest version at the time of writing.
How to do it...
We create an instance of NTPClient and then we call the request() method on it by passing the NTP server address.
Listing 1.11 shows how to print the current time from the internet time server as follows:
#!/usr/bin/env python # Python Network Programming Cookbook,
Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12
and Python 3.5.2. # It may run on any other version with/without
modifications. import ntplib from time import ctime def print_time(): ntp_client = ntplib.NTPClient() response = ntp_client.request('pool.ntp.org') print (ctime(response.tx_time)) if __name__ == '__main__': print_time()
In my machine, this recipe shows the following output:
$ python 1_11_print_machine_time.py Fri Jun 2 16:01:35 2017
How it works...
Here, an NTP client has been created and an NTP request has been sent to one of the internet NTP servers, pool.ntp.org. The ctime() function is used for printing the response.