How to Change the NTP Server in MicroPython (Raspberry Pi Pico W)

Raspberry Pi Pico W board

The Raspberry Pi Pico W doesn't have a battery-backed clock, so every time it powers up it has no idea what the date or time is. MicroPython's ntptime module fixes that by fetching the time from an internet time server (an NTP server). By default it asks pool.ntp.org, but you can point it at any NTP server you like, such as Google's public time service, a server closer to you, or your own router. Here's how to change the NTP host and set the clock to your local time.

The device must be connected to the internet. Tested on a Raspberry Pi Pico W.

What you need

MicroPython code

Fill in your WiFi name and password, set UTC_OFFSET_HOURS to your time zone and run the script:

import network
import ntptime
import time

SSID = "YOUR SSID"
PASSWORD = "YOUR PASSWORD"
NTP_HOST = "time.google.com"   # or "pool.ntp.org", or your router's IP address
UTC_OFFSET_HOURS = 0           # your time zone, e.g. 2 or -5 (use 5.5 for UTC+5:30)

# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)

# Wait up to 15 seconds for the connection
for _ in range(15):
    if wlan.isconnected():
        break
    time.sleep(1)

if not wlan.isconnected():
    raise RuntimeError("WiFi connection failed")

print("WiFi connected, IP address:", wlan.ifconfig()[0])

# Important: give the network a few seconds to settle after connecting.
# Requesting the time too quickly causes intermittent failures.
time.sleep(5)

# Change the NTP host, then set the clock (retrying a few times)
ntptime.host = NTP_HOST
for attempt in range(3):
    try:
        ntptime.settime()   # sets the Pico's real-time clock to UTC
        break
    except OSError as e:
        print("NTP request failed, retrying:", e)
        time.sleep(2)
else:
    raise RuntimeError("Could not get the time from " + NTP_HOST)

# After settime() the clock is in UTC, so apply your offset manually
utc = time.localtime()
local = time.localtime(time.time() + int(UTC_OFFSET_HOURS * 3600))

sign = "+" if UTC_OFFSET_HOURS >= 0 else "-"
offset_h = int(abs(UTC_OFFSET_HOURS))
offset_m = int((abs(UTC_OFFSET_HOURS) - offset_h) * 60)

print("UTC time:   {:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(*utc[0:6]))
print("Local time: {:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} UTC{}{:02d}:{:02d}".format(
    *(local[0:6] + (sign, offset_h, offset_m))))

Update: an earlier version of this code printed the UTC time with a time zone label attached but didn't actually shift the time to the local zone. The version above applies the offset properly and also retries if the time server doesn't answer.

How the code works

  • Connecting to WiFi – the script joins your network and waits up to 15 seconds for a connection before giving up.
  • The pause after connecting – asking for the time the instant WiFi connects often fails. Waiting a few seconds makes it far more reliable.
  • ntptime.host = NTP_HOST – this is the line that changes the time server. Set it before calling settime().
  • ntptime.settime() – sends a request to the server and sets the Pico's internal real-time clock. The time is always set to UTC.
  • Applying your time zone – because the clock is in UTC, the code adds your offset in seconds to time.time() and converts the result back into a date and time with time.localtime().

Choosing an NTP host

  • pool.ntp.org – the default. A large volunteer-run pool of servers, and a good general choice.
  • time.google.com – Google's public NTP service. It's fast and reliable, but it "smears" leap seconds over a day instead of adding them in one go, so don't mix it with other servers on the same device.
  • Regional pools – pool.ntp.org has country and continent sub-domains which can give quicker responses.
  • Your router or a local server – many routers can act as a time server. Using its IP address keeps time requests on your own network.

Things to keep in mind

  • No daylight saving – MicroPython doesn't know about daylight saving time, so you'll need to change the offset when the clocks change, or add your own rules.
  • The time is lost at power-off – call the sync again each time the board starts. For long-running projects, re-sync every few hours, since the Pico's clock slowly drifts.
  • Don't hammer the server – syncing once at start-up and then every few hours is plenty. Public time servers may stop responding to devices that ask too often.

Troubleshooting

  • OSError: [Errno 110] ETIMEDOUT – the server didn't reply in time. Increase the pause after connecting, check the host name is spelled correctly, or try a different server.
  • Works on one network but not another – some workplace and guest networks block NTP (UDP port 123). Try a different network or your router's IP address as the host.
  • The time is out by whole hours – check the sign and value of UTC_OFFSET_HOURS. Time zones east of UTC are positive and west of UTC are negative.

This post contains affiliate links. As an Amazon Associate I earn from qualifying purchases, at no extra cost to you.

Popular posts from this blog

How to Connect a Raspberry Pi Pico W to WiFi with MicroPython

How to Blink an LED on the Raspberry Pi Pico and Pico W (MicroPython)