EOFFJM
Posts: 22
Joined: Thu Jan 24, 2019 6:23 pm

Connection to NTP server

Mon Jul 08, 2019 4:34 pm

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.

User avatar
neilgl
Posts: 2111
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near Aston Martin factory

Re: Connection to NTP server

Mon Jul 08, 2019 4:46 pm

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

User avatar
DougieLawson
Posts: 38883
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Connection to NTP server

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)
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

EOFFJM
Posts: 22
Joined: Thu Jan 24, 2019 6:23 pm

Re: Connection to NTP server

Mon Jul 08, 2019 5:35 pm

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!

Return to “Troubleshooting”