Micro Python - how to change NTP host

Raspberry Pi Pico
To change the default NTP host on Micro python

Device must be connected to internet. Tested on Raspberry Pi Pico W.








MICRO PYTHON CODE:

import network

import ntptime

import time




# Connect to WiFi

wlan = network.WLAN(network.STA_IF)

wlan.active(True)

# Your Username and Password goes here

wlan.connect("USERNAME", "PASSWORD")

print("WiFi connected? ",wlan.isconnected())

print(wlan.ifconfig())




# Important sleep time after connecting to wifi.

# Proceeding too fast after connecting will result in intermittent failures.

time.sleep(5)




# Get time and print

ntptime.host = 'time.google.com'

ntptime.settime()

print("Retrieved time: ",time.localtime())




# Get the current local time

local_time = time.localtime()




# Replace below value with your timezone hours. "+10" or "-10" for example.

offset_str = "+10" # Replace this with your desired offset




# Convert the offset string to a UTC offset in seconds

offset_hours = int(offset_str)

offset_minutes = (offset_hours % 1) * 60

utc_offset_sec = int(offset_hours) * 3600 + int(offset_minutes) * 60




# Determine the sign of the offset

utc_offset_sign = "-" if utc_offset_sec > 0 else "+"




# Format the local time into a string in a standard time format with timezone offset

standard_time = "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d} {}{:02d}:{:02d}".format(

local_time[0], local_time[1], local_time[2], local_time[3], local_time[4], local_time[5], utc_offset_sign, abs(offset_hours), abs(offset_minutes))




# Print the standard time

print(standard_time)


Popular posts from this blog

Review - E-Yooso Z-88 Keyboard

Replacing Viking GB455 Mulcher Blades