time – time related functions
This module implements a subset of the correspondingCPythonmodule,as described below. For more information, refer to the originalCPython documentation:time.
Thetime module provides functions for getting the current time and date,measuring time intervals, and for delays.
Time Epoch: The unix, windows, webassembly, alif, mimxrt and rp2 portsuse the standard for POSIX systems epoch of 1970-01-01 00:00:00 UTC.The other embedded ports use an epoch of 2000-01-01 00:00:00 UTC.Epoch year may be determined withgmtime(0)[0].
Maintaining actual calendar date/time: This requires aReal Time Clock (RTC). On systems with underlying OS (including someRTOS), an RTC may be implicit. Setting and maintaining actual calendartime is responsibility of OS/RTOS and is done outside of MicroPython,it just uses OS API to query date/time. On baremetal ports howeversystem time depends onmachine.RTC() object. The current calendar timemay be set usingmachine.RTC().datetime(tuple) function, and maintainedby following means:
By a backup battery (which may be an additional, optional component fora particular board).
Using networked time protocol (requires setup by a port/user).
Set manually by a user on each power-up (many boards then maintainRTC time across hard resets, though some may require setting it againin such case).
If actual calendar time is not maintained with a system/MicroPython RTC,functions below which require reference to current absolute time maybehave not as expected.
Functions
- time.gmtime([secs])
- time.localtime([secs])
Convert the timesecs expressed in seconds since the Epoch (see above) into an8-tuple which contains:
(year,month,mday,hour,minute,second,weekday,yearday)Ifsecs is not provided or None, then the current time from the RTC is used.The
gmtime()function returns a date-time tuple in UTC, andlocaltime()returns adate-time tuple in local time.The format of the entries in the 8-tuple are:
year includes the century (for example 2014).
month is 1-12
mday is 1-31
hour is 0-23
minute is 0-59
second is 0-59
weekday is 0-6 for Mon-Sun
yearday is 1-366
- time.mktime(date_time_tuple)
This is inverse function of localtime. It’s argument is a full 8-tuplewhich expresses a time as per localtime. It returns an integer which isthe number of seconds since the time epoch.
- time.sleep(seconds)
Sleep for the given number of seconds. Some boards may acceptseconds as afloating-point number to sleep for a fractional number of seconds. Note thatother boards may not accept a floating-point argument, for compatibility withthem use
sleep_ms()andsleep_us()functions.
- time.sleep_ms(ms)
Delay for given number of milliseconds, should be positive or 0.
This function will delay for at least the given number of milliseconds, butmay take longer than that if other processing must take place, for exampleinterrupt handlers or other threads. Passing in 0 forms will still allowthis other processing to occur. Use
sleep_us()for more precise delays.
- time.sleep_us(us)
Delay for given number of microseconds, should be positive or 0.
This function attempts to provide an accurate delay of at leastusmicroseconds, but it may take longer if the system has other higher priorityprocessing to perform.
- time.ticks_ms()
Returns an increasing millisecond counter with an arbitrary reference point, thatwraps around after some value.
The wrap-around value is not explicitly exposed, but we willrefer to it asTICKS_MAX to simplify discussion. Period of the values isTICKS_PERIOD = TICKS_MAX + 1.TICKS_PERIOD is guaranteed to be a power oftwo, but otherwise may differ from port to port. The same period value is usedfor all of
ticks_ms(),ticks_us(),ticks_cpu()functions (forsimplicity). Thus, these functions will return a value in range [0 ..TICKS_MAX], inclusive, totalTICKS_PERIOD values. Note that onlynon-negative values are used. For the most part, you should treat values returnedby these functions as opaque. The only operations available for them areticks_diff()andticks_add()functions described below.Note: Performing standard mathematical operations (+, -) or relationaloperators (<, <=, >, >=) directly on these value will lead to invalidresult. Performing mathematical operations and then passing their resultsas arguments to
ticks_diff()orticks_add()will also lead toinvalid results from the latter functions.
- time.ticks_us()
Just like
ticks_ms()above, but in microseconds.
- time.ticks_cpu()
Similar to
ticks_ms()andticks_us(), but with the highest possible resolutionin the system. This is usually CPU clocks, and that’s why the function is named thatway. But it doesn’t have to be a CPU clock, some other timing source available in asystem (e.g. high-resolution timer) can be used instead. The exact timing unit(resolution) of this function is not specified ontimemodule level, butdocumentation for a specific port may provide more specific information. Thisfunction is intended for very fine benchmarking or very tight real-time loops.Avoid using it in portable code.Availability: Not every port implements this function.
- time.ticks_add(ticks,delta)
Offset ticks value by a given number, which can be either positive or negative.Given aticks value, this function allows to calculate ticks valuedeltaticks before or after it, following modular-arithmetic definition of tick values(see
ticks_ms()above).ticks parameter must be a direct result of calltoticks_ms(),ticks_us(), orticks_cpu()functions (or from previouscall toticks_add()). However,delta can be an arbitrary integer numberor numeric expression.ticks_add()is useful for calculating deadlines forevents/tasks. (Note: you must useticks_diff()function to work withdeadlines.)Examples:
# Find out what ticks value there was 100ms agoprint(ticks_add(time.ticks_ms(),-100))# Calculate deadline for operation and test for itdeadline=ticks_add(time.ticks_ms(),200)whileticks_diff(deadline,time.ticks_ms())>0:do_a_little_of_something()# Find out TICKS_MAX used by this portprint(ticks_add(0,-1))
- time.ticks_diff(ticks1,ticks2)
Measure ticks difference between values returned from
ticks_ms(),ticks_us(),orticks_cpu()functions, as a signed value which may wrap around.The argument order is the same as for subtractionoperator,
ticks_diff(ticks1,ticks2)has the same meaning asticks1-ticks2.However, values returned byticks_ms(), etc. functions may wrap around, sodirectly using subtraction on them will produce incorrect result. That is whyticks_diff()is needed, it implements modular (or more specifically, ring)arithmetic to produce correct result even for wrap-around values (as long as they nottoo distant in between, see below). The function returnssigned value in the range[-TICKS_PERIOD/2 ..TICKS_PERIOD/2-1] (that’s a typical range definition fortwo’s-complement signed binary integers). If the result is negative, it means thatticks1 occurred earlier in time thanticks2. Otherwise, it means thatticks1 occurred afterticks2. This holdsonly ifticks1 andticks2are apart from each other for no more thanTICKS_PERIOD/2-1 ticks. If that doesnot hold, incorrect result will be returned. Specifically, if two tick values areapart forTICKS_PERIOD/2-1 ticks, that value will be returned by the function.However, ifTICKS_PERIOD/2 of real-time ticks has passed between them, thefunction will return-TICKS_PERIOD/2 instead, i.e. result value will wrap aroundto the negative range of possible values.Informal rationale of the constraints above: Suppose you are locked in a room with nomeans to monitor passing of time except a standard 12-notch clock. Then if you look atdial-plate now, and don’t look again for another 13 hours (e.g., if you fall for along sleep), then once you finally look again, it may seem to you that only 1 hourhas passed. To avoid this mistake, just look at the clock regularly. Your applicationshould do the same. “Too long sleep” metaphor also maps directly to applicationbehaviour: don’t let your application run any single task for too long. Run tasksin steps, and do time-keeping in between.
ticks_diff()is designed to accommodate various usage patterns, among them:Polling with timeout. In this case, the order of events is known, and you will dealonly with positive results of
ticks_diff():# Wait for GPIO pin to be asserted, but at most 500usstart=time.ticks_us()whilepin.value()==0:iftime.ticks_diff(time.ticks_us(),start)>500:raiseTimeoutError
Scheduling events. In this case,
ticks_diff()result may be negativeif an event is overdue:# This code snippet is not optimizednow=time.ticks_ms()scheduled_time=task.scheduled_time()ifticks_diff(scheduled_time,now)>0:print("Too early, let's nap")sleep_ms(ticks_diff(scheduled_time,now))task.run()elifticks_diff(scheduled_time,now)==0:print("Right at time!")task.run()elifticks_diff(scheduled_time,now)<0:print("Oops, running late, tell task to run faster!")task.run(run_faster=true)
Note: Do not pass
time()values toticks_diff(), you should usenormal mathematical operations on them. But note thattime()may (and will)also overflow. This is known ashttps://en.wikipedia.org/wiki/Year_2038_problem .
- time.time()
Returns the number of seconds, as an integer, since the Epoch, assuming thatunderlying RTC is set and maintained as described above. If an RTC is not set, thisfunction returns number of seconds since a port-specific reference point in time (forembedded boards without a battery-backed RTC, usually since power up or reset). If youwant to develop portable MicroPython application, you should not rely on this functionto provide higher than second precision. If you need higher precision, absolutetimestamps, use
time_ns(). If relative times are acceptable then use theticks_ms()andticks_us()functions. If you need calendar time,gmtime()orlocaltime()without an argument is a better choice.Difference to CPython
In CPython, this function returns number ofseconds since Unix epoch, 1970-01-01 00:00 UTC, as a floating-point,usually having microsecond precision. With MicroPython, only Unix portuses the same Epoch, and if floating-point precision allows,returns sub-second precision. Embedded hardware usually doesn’t havefloating-point precision to represent both long time ranges and subsecondprecision, so they use integer value with second precision. Some embeddedhardware also lacks battery-powered RTC, so returns number of secondssince last power-up or from other relative, hardware-specific point(e.g. reset).