Posted: 03:27pm 09 Apr 2025 |
Copy link to clipboard |
 Print this post |
|
So, a while back (2023) I was looking for a way to get accurate time into my WEBMITE for a personal alarm clock project. One of the things that was tripping me up was making the Daylight Savings adjustments and offset from UTC for East Coast USA.
One of my solutions was to go beyond just NTP and employ a web-based time API, such as "http://worldtimeapi.org/api/timezone/America/New_York". And... it worked really well. I could snag the Timezone offset value and with that response item in JSON format, I could make a proper "web ntp offset, 'host'" query. From then on, my time would be all set.
Except...
The API services at http://worldtimeapi.org started responding to every request with curl: (52) Empty reply from server for any query made, so my solution was now dead. Being someone else's free service, fixing it is beyond my control.
But I do have a spare Raspberry Pi available, so I went full in-house mode and installed an NTP server on it, followed by a Python/FLASK script that created my very own TIME API for various purposes but that would give me what I needed to supply to the "web ntp" command.
Here is my test code:
' Program: TimeApi.bas ' Author: pete willard ' Version: 2.0 ' Target: WEBMITE ' Date: 2025/04/9 ' Time: 10:50:29 ' Reference: '============================================================================== ' TTTTT III M M EEEEE AAA PPPP III BBBB AAA SSSS ' T I MM MM E A A P P I B B A A S ' T I M M M EEEE AAAAA PPPP I BBBB AAAAA SSS ' T I M M M E A A P I .. B B A A S ' T III M M EEEEE A A P III .. BBBB A A SSSS '============================================================================== ' ' KEEPING IT IN-HOUSE '--------------------- ' get: http://192.168.1.27:7777/time ' There is a python time api service running on a Raspberry Pi ' on port 7777 ' This Raspberry Pi also runs a local NTP server '------------------------------------------------------------- ' HTTP GET 192.168.27:7777/time ' RESPONSE: '{ ' "current_time": "09-04-2025 10:17:53", ' "timezone": "America/New_York", ' "utc_offset": "-04:00" '} ' For my immediate purpose, I only need the 'utc_offset' ' ' NOTE:For some reason, the API call wants 2 carriage returns on a GET request. '=====[ CONFIGURATION ]========================================================
'=====[ VARIABLES ]============================================================ Dim buff%(1024) ' Response Buffer Dim CRLF$ = Chr$(10)+Chr$(13) Dim GetRequest$ = "GET /time"+CRLF$+CRLF$ Dim ADDRESS$ = "192.168.1.27" ' JSON String Values DIM CTIME$ DIM CTIMEZONE$ DIM COFFSET$ ' What we pass to WEB NTP for an offset DIM Integer COFFSET_adj ' Utilize VT100 escape codes Dim STRING EL$ = Chr$(27)+"[" '=====[ SUBROUTINES ]========================================================== Sub TCLS ' clear Terminal Screen Print el$;"2J"; HOME End Sub
Sub HOME ' Cursor top left Print el$;"H"; End Sub
Sub AT Row,Col ' Print At Location Print el$;;Str$(Row);"H";el$;Str$(Col);"G"; End Sub '============================================================================== '=====[ MAIN CODE ]============================================================ HOME TCLS
' Keep debugging content in for now. Print "Open Session" WEB OPEN TCP CLIENT Address$,7777 Print "Make Request" WEB TCP CLIENT REQUEST GetRequest$, buff%(),10000 Print "Close Session" WEB CLOSE TCP CLIENT
COFFSET$ = Json$(buff%(),"utc_offset") CTIME$ = Json$(buff%(),"current_time") CTIMEZONE$ = Json$(buff%(),"timezone")
Coffset_Adj = val(left$(coffset$,3))
' Make call to local NTP server with offset value WEB ntp COFFSET_ADJ,"192.168.1.27"
' Time is now set from local NTP server and with proper local offset Print Time$ Print Date$
And some straightforward Python code to support it...
# Simple Python API that includes time and UTC offset details # RUN as a service from flask import Flask, jsonify
from datetime import datetime from zoneinfo import ZoneInfo
app = Flask(__name__)
@app.route('/time', methods=['GET']) def get_time(): tz = ZoneInfo("America/New_York") now = datetime.now(tz) formatted_time = now.strftime('%d-%m-%Y %H:%M:%S') offset = now.utcoffset() offset_hours = int(offset.total_seconds() // 3600) offset_minutes = int((offset.total_seconds() % 3600) // 60) utc_offset = f"{offset_hours:+03}:{abs(offset_minutes):02}" return jsonify({ "current_time": formatted_time, "timezone": "America/New_York", "utc_offset": utc_offset })
if __name__ == '__main__': app.run(debug=True, host='0.0.0.0',port=7777)
The Python code is installed as a service that starts automatically...
Open Session Connected Make Request Close Session ntp address 192.168.1.27 got ntp response: 09/04/2025 10:58:58 10:58:58 09-04-2025:
Nice and easy. Edited 2025-04-10 01:35 by pwillard |