In this Python article we are going to learn How to Print Current Time in Python, 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. 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.
Learn More on Python
- Python Socket Programming
- Working with Python Pyglet Library
- Python Speech Recognition For Beginners
- PyQtGraph Tutorial in Python
- Convert Python PY File to EXE
What is NTPLib ?
This module offers a simple interface to query NTP servers from Python. It also provides utility functions to translate NTP fields values to text (mode, leap indicator…). Since it’s pure Python, and only depends on core modules, it should work on any platform with a Python implementation.
Installation
You can use pip for the installation.
1 |
pip install ntplib |
So now this is the complete code
1 2 3 4 5 6 7 8 9 10 11 |
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)) print_time() |
Here is 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.
Run the complete code and this is the result.