Local time and timezone support for MicroPython (meta-discussion) #12378
Replies: 10 comments 18 replies
-
Maybe this isn't true actually, if the |
Beta Was this translation helpful? Give feedback.
-
I personally use the datetime module because it supports creating tz objects with daylight savings support etc.... I like the concept of using the datetime module because it is compatible with cpython however I feel it is a little bit slow, when compared to doing a simple add/subtract of seconds. You mention that |
Beta Was this translation helpful? Give feedback.
-
Adding the least amount of code #695 ntptime.py#L45-L46 is my idea, which is also derived from peterhinch/ntptime.py#L36C19. It seems like there are some drawbacks to this? I mean, will this cause problems in practical application? During my test, after setting the time zone, the |
Beta Was this translation helpful? Give feedback.
-
There are two application cases. [EDITED]
As an example of 1. see this module which is a minimal |
Beta Was this translation helpful? Give feedback.
-
One detail I haven’t seen mentioned yet: Since currently |
Beta Was this translation helpful? Give feedback.
-
Please don't generalize for simple countries. Consider Canada:
It's very complicated and very confusing: Time zones and daylight saving time - National Research Council Canada. |
Beta Was this translation helpful? Give feedback.
-
If the shakers & movers are going to make local time easily available in micropython it might be worth fixing some of the other time related annoyances? In particular the inconsistency between datetime (which uses the year, month, day-of-month, day-of-week, hours, mins, secs, day-of year format) and mktime or gmtime (which use the year, month, day-of-month, hour, mins, secs, day-of-week, day-of-year format). Interestingly, to me at least, if your project uses cellular connectivity most LTE modems will supply local time via the 4G tower. Even then you are not out of the woods when your application blunders into the twilight zone around 3am twice a year when a whole hour of local time either vanishes or pops into existence like some magical sub atomic particle. |
Beta Was this translation helpful? Give feedback.
-
This is indeed interesting and would be a good optimization, making the ESP32 implementation smaller. However, it's probably more compatible and less maintenance effort to have the same implementation for all architectures.
Having three variables (time zone name, offset and DST indicator) and setting these variables sounds like a simple solution. To use that, the programmer will have to write a task that wakes up when a transition between DST and non-DST occurs, and set the new variables. However, there is no guarantee that this task, be it asyncio, timer or thread, will wake up exactly at the specified time. This task to set the time zone may be triggered a bit late, and other code can call In summary: it might be better to process the time zone rule each time The same reasoning applies to an RTC. I believe the RTC should be set to UTC (never to the local time) and the time zone rules should be applied by software each time the RTC is read. There are several advantages: it makes it possible to work with several time zones, and there is no need for a time critical task to update the RTC on time zone transitions. In fact, if the RTC is set to a a certain local time, it's very tricky to move it back to UTC or to another time zone.
This indeed would be very useful. Due to space restraints, this functionality most likely might be mip installable as an optional module. To be compatible with big Python, I think having a MicroPython specific time zone data base may be a lot of work. The database has to be updated weekly or even more frequently. It's probably better to have everyone lookup or request the needed POSIX string. Updating time zone rules via mip install Continent/City) may be interesting, but need not be part of MicroPython for now. Just to illustate: In some countries, time zone rules have been changed on short notice (a week before the transition). This must be handled as OTA emergency patch. There are many ways available today to support OTA updates, no need to do something time zone specific. |
Beta Was this translation helpful? Give feedback.
-
guys here first most impordent is to connect board to wifi n internet using network commands then this is simple micropython code to see and sync ur current boad to network time Njoy import time def getNow(UTC_OFFSET=+5.5): if name == "main": """ Usage (assuming a it is connected to wifi with internet network connection):
""" |
Beta Was this translation helpful? Give feedback.
-
If the problem is that there is no marker for the time zone, you could parse
ntptime.settime()
rtc = machine.RTC()
def dateTimeToISO(dateTime):
return "{:04d}-{:02d}-{:02d}T{:02d}:{:02d}:{:02d}.{:03d}Z".format(
dateTime[0],
dateTime[1],
dateTime[2],
dateTime[4],
dateTime[5],
dateTime[6],
dateTime[7] // 1000,
)
dateTimeToISO(rtc.datetime()) |
Beta Was this translation helpful? Give feedback.
-
Summarising this common problem and the current best solutions and possibility for a long-term fix.
Problem
Some embedded applications care about the local time. MicroPython always uses UTC timezone and its time module is generally not timezone or localtime aware.
This seems to usually impact folks using ntptime module from micropython-lib. This returns UTC (NTP protocol only uses UTC). How to display a local time somewhere?
Current Simplest Solutions ✔️
mip install datetime
from micropython-lib and convert the timestamp as shown here (thanks @jimmo).localtime()
function, as demonstrated by @MrEbbinghaus (thanks!).Other Proposed Solutions
The following solutions add timezone offset support to the ntptime module:
This is clearly something people run into a lot!
Long term solutions
As others, including maintainers, have already said in the linked discussions, the official micropython-lib
ntptime
module should keep working with UTC. However, it would clearly be useful to have an easy way to convert timestamps to a local timezone in MicroPython.There are a range of possible solutions here, from a simple "local time offset" variable to a full POSIX timezone format compliant implementation that automatically switches for DST, etc.
Current Status
time.gmtime()
andtime.localtime()
are literally the same function.time.gmtime()
andtime.localtime()
in MicroPython is different to CPython. MicroPython returns a tuple with 8 of the 9 indexed fields found in CPythonstruct_time
. CPython's result has a ninthtm_isdst
field, plus named access to those 9 fields and the extra fieldstm_zone
andtm_gmtoff
..patch
already in the source tree to re-enable naive datetime support on platforms with meaningfultime.localtime()
❤️ .(An aside, CPython's
time
module behaviour on Linux was a little different to my initial naive expectation.time.timezone
,time.alttime
,time.dst
variables are writable but changing them doesn't change thetime.localtime()
result. To do this requires updatingTZ
(either locally or globally) and callingtime.tzset()
, which then updates those three variables to match the result ofTZ
. This makes sense (otherwise what happens when DST transitions and a CPython process is running?) but I still had naively expected changing the variables to have some effect.)Existing port support
time.localtime()
that calls the POSIXlocaltime()
function. It could easily add more timezone support in the same way (i.e.tzset()
), if there was a use for that.TZ
environment variable and setting it but I don't know how much binary size this adds.) Some work has been done on these already, for example @tve has this PR for ESP32.Way forward
This is just me spitballing at the moment:
time.tzset()
rather than requiring theTZ
environment variable to be set. (Currently only Unix port has a Python interface for setting environment variables, but we could also cheat and expose something likeesp32.TZ
.)machine.RTC.local_tz
where a timezone offset in seconds can be written (maybe evenmicropython.local_tz
?). If the application sets this,time.localtime()
applies this offset. (The obvious choice here would be to implementtime.timezone
, etc. and use those, but that isn't how CPython uses them. 😿)CET-1
), or supporting the full POSIX timezone strings (CET-1CEST,M3.5.0,M10.5.0/3
).struct_time
fromgmtime()
andlocaltime()
, making the results compatible to CPython.mip install micropython-timezone
(or similar) that adds a way to set a POSIX timezone specifier string which is then parsed in Python and automatically applied to the system. This would require adding some kind of hook totime.localtime
or having the micropython-lib package monkey patch that function, though, and I don't know if that would be acceptable.Beta Was this translation helpful? Give feedback.
All reactions