Thursday, 28 May 2015

Setting the time on a Raspberry Pi over HTTP/without NTP

One of my Raspberry Pis is installed in a location with a restrictive firewall, which means it is not possible to get the time and date using the NTP service, and I am not aware of a local NTP server.

I found an alternative which was to update the time over HTTP by using www.timeapi.org to request the time and date, in the correct format, and then use this to set the time. To set the time, I copied the code posted to the Raspberry Pi forums by ytsentas however with a modification.

The problem was that the URL originally specified the "I" flag for the format, which requests the number of hours in a 12 hour format. So changing this to "H" gives a 24 hour number. More information about the formating string can be found here (original website is no longer available).

The following batch script can be used to update the time and date.
#!/bin/bash
# Visit www.timeapi.org to find the correct url for your timezone. Then replace the url in the first line

time=$(wget http://www.timeapi.org/utc/in+one+hours?format=%25d%20%25b%20%25Y%20%25H:%25M:%25S -q -O -)
echo "Time set to:"
sudo date -s "`echo $time`"

The script needs to be saved as filename.sh, and then run the command
chmod 755 filename.sh
Which will allow the script to be executed. To execute the script from the same directory, enter:
./filename.sh