Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 18:49 10 May 2025 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : Time API

Author Message
pwillard
Guru

Joined: 07/06/2022
Location: United States
Posts: 307
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
 
matherp
Guru

Joined: 11/12/2012
Location: United Kingdom
Posts: 10067
Posted: 03:35pm 09 Apr 2025
Copy link to clipboard 
Print this post

  Quote   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

Have a look at Geoff's watering controller - he does it all on the WebMite using openweathermap to get UTC offset + daylight saving
 
pwillard
Guru

Joined: 07/06/2022
Location: United States
Posts: 307
Posted: 03:37pm 09 Apr 2025
Copy link to clipboard 
Print this post

Huh, I never even looked at that code, but yeah, I just needed something that would give me the offset for where I live.

My issue also highlights the issues related to relying on a free web api.
Edited 2025-04-10 01:41 by pwillard
 
Print this page


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2025