Quick time zone (offset) calculation snippet

CircuitPython on hardware including Adafruit's boards, and CircuitPython libraries using Blinka on host computers.

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
jwtadmin
 
Posts: 53
Joined: Thu Jan 07, 2016 2:50 pm

Quick time zone (offset) calculation snippet

Post by jwtadmin »

I am working on a project that has only a GPS device to get the time. However in my research there isn't an easy way to tell CircuitPython you are in a certain time zone or to tell the adafruit_gps library to calculate local time in the local offset or time zone. The GPS can return the time in UCT and you can sync that to the local time by using the rtc.set_time_source(gps) call. However this creates local time in UTC - great for data logging - but bad for my display time.

Here is a quick snippet of code I found that works well to calculate a -5 hour EST time structure from time.localtime() in UTC

time.localtime(time.time()-18000)

while I was familiar with time.localtime() returning the date time structure of the internal clock - I wasn't aware that it is also a function to return a time structure based on epoch time.

So in this code I use time.time() to generate the epoch time - then subtract 5 hours (18000 seconds) then ask time.localtime to return a time structure.

I can easily ask it for the hour time.localtime(time.time()-18000).tm_hour when I want to display the -5 EST time without having to do math on the day and date.

What would be great is if CP had a time_offset setting that we could set for time.localtime and even an AM/PM option.

Hope this helps the next person looking to do this - or me when I go searching in a year or two and stumble upon my own code :-)

Locked
Please be positive and constructive with your questions and comments.

Return to “Adafruit CircuitPython”