Page 1 of 1

Connection to NTP server

Posted: Mon Jul 08, 2019 4:34 pm
by EOFFJM

Code: Select all

import ntplib
from datetime import datetime, timezone
c = ntplib.NTPClient()
        # Provide the respective ntp server ip in below function
response = c.request('uk.pool.ntp.org', version=3)
response.offset
        # UTC timezone used here, for working with different timezones you can use [pytz library][1]
print (datetime.fromtimestamp(response.tx_time, timezone.utc))
I tried the following code on Rasppi to connect to NTP server and get the time. But I get OSError [Errorno 101] Network is unreachable.
Does anyone know why I get this? I tried it on a Windows PC and it works fine. Windows PC has got python 3.7 and Rasppi has python 3.5. Is it because of the python version?
I am trying to connect to the NTP server for synchronization between multiple python files on different Rasppis, by the way.

Thanks.

Re: Connection to NTP server

Posted: Mon Jul 08, 2019 4:46 pm
by neilgl
Maybe your network was not connected at that time. Your code (forumntp.py) works fine on my pi

Code: Select all

python3 forumntp.py
2019-07-08 16:42:18.072624+00:00
$ python3 --version
Python 3.5.3

Re: Connection to NTP server

Posted: Mon Jul 08, 2019 5:03 pm
by DougieLawson
They don't include NTP by default in Stretch or Buster.

sudo apt install ntp
sudo timedatectl set-ntp 1
ntpq -p -n


Then you can try connecting to localhost or 127.0.0.1 or 192.168.3.14 (ip address for your RPi)

Re: Connection to NTP server

Posted: Mon Jul 08, 2019 5:35 pm
by EOFFJM
DougieLawson wrote:
Mon Jul 08, 2019 5:03 pm
They don't include NTP by default in Stretch or Buster.

sudo apt install ntp
sudo timedatectl set-ntp 1
ntpq -p -n


Then you can try connecting to localhost or 127.0.0.1 or 192.168.3.14 (ip address for your RPi)
Thank you very much! It works now!