0
def grabtime(dst):
    global sec
    global minute
    global hour
    global day
    global month
    global year
    gps.update()
    sec = gps.timestamp_utc.tm_sec
    minute = gps.timestamp_utc.tm_min
    hour = gps.timestamp_utc.tm_hour + dst
    day = gps.timestamp_utc.tm_day
    month = gps.timestamp_utc.tm_month
    year = gps.timestamp_utc.tm_hour
    if dst != 0:
        if hour > 23:
            hour = 0
            day += 1

        # This part checks how many days are in the month, and so when it should go to the next month.
        if day > 31 and month in [1,3,5,7,8,10,12]:
            day = 0
            month += 1
        elif day > 30 and month in [4,6,9,11]:
            day = 0
            month += 1
        elif day > 28 and month == 2 and not CheckLeap(year):
            day = 0
            month += 1
        elif day > 28 and month == 2 and CheckLeap(year):
            day = 0
            month += 1

        if month > 12 and day > 31:
            month = 1
            year += 1

I'm making a GPS clock using CircuitPython. Since GPS always outputs at UTC with no Daylight Savings Time, I wanted to give the ability to change the offset of time. However, at the moment I can't really test this since it's the middle of July, and I don't really want to wait to test the code. Does this code look like it would implement DST and time zones correctly? I just need a second opinion, as I'm unsure that this will work.

Or, is there a library that does this for me (I tried looking for one but couldn't find it)?

Just to clarify, CheckLeap() detects if the year is a leap year. I'm using the adafruit_circuitpython_gps library, if that means anything.

1 Answers1

0

You can use pytz module for timezones.

import pytz

utc_now = pytz.utc.now()


pst_now = pytz.timezone('US/Pacific').localize(utc_now)

pst_utc_offset = pst_now - utc_now

print(pst_now)

And for your implementation for dst, I would add a check to make sure that the day and month don't overflow. For example, if the current time is 11:59 PM on March 31st and you set the DST offset to 2, then the code would try to set the hour to 1:01 AM on April 1st, which would overflow the day and month. You can fix this by adding a check to make sure that the day and month are still within their valid ranges.

Moid
  • 410
  • 5
  • 9
  • So pytz does work with CircuitPython? I haven't seen it mentioned anywhere. Probably should have added that in the tags. – Commodore 64 Jul 07 '23 at 15:54
  • Yes. https://github.com/adafruit/adafruit-circuitpython-weekly-meeting/blob/main/generate_calendar.py – Moid Jul 07 '23 at 16:01
  • The `#!/usr/bin/python3` probably means that code is written for Linux. I think that it's written for making a meeting schedule, on a computer. Correct me if I'm wrong, though. – Commodore 64 Jul 07 '23 at 16:04