adafruit / Adafruit_CircuitPython_datetime

Basic date and time types. Implements a subset of the CPython datetime module.
MIT License
4 stars 9 forks source link

Cannot add 'date' and 'timedelta' types #17

Open strimmer opened 2 years ago

strimmer commented 2 years ago

I'm trying to calculate tomorrow's date. The approach I'm taking is as follows: adate = adafruit_datetime.date (2022, 03, 31) delta = adafruit_datetime.timedelta(days=1) bdate = adate + delta

I then get the following error: Traceback (most recent call last): File "", line 1, in TypeError: unsupported types for add: 'date', 'timedelta'

Looking for the functionality provided by the datetime module as documented in the supported operations section here: https://docs.python.org/3/library/datetime.html#datetime.date.day

Currently running the following Circuit Python according to boot_out.txt: Adafruit CircuitPython 7.1.1 on 2022-01-14; Adafruit MagTag with ESP32S2 Board ID:adafruit_magtag_2.9_grayscale

regulatre commented 2 years ago

I've encountered the same challenge. I've considered converting to Epoch, then adding seconds, then back to iso, but I am seeing an inability of the ESP32 to perform math against large numbers like epoch (eg. 1660233725 + 1), likely due to the number of bits required to store such a large number, approximation may be causing this behavior. At any rate, for now I'll be storing the ISO NTP time along with an uptime seconds shift since that uptime so that on the receive side I can perform the time shift calculation associated with the samples.

Neradoc commented 2 years ago

Yeah it is supported in C python, so it would be nice to have. You can use datetime objects instead of dates as a workaround:

>>> adate = adafruit_datetime.datetime(2022, 3, 31)
>>> delta = adafruit_datetime.timedelta(days=1)
>>> bdate = adate + delta
>>> bdate.date()
datetime.date(2022, 4, 1)

And convert between them, though it seems a little awkward.

>>> t0 = adafruit_datetime.time(0)
>>> adatetime  = adafruit_datetime.datetime.combine(adate, t0)
>>> adatetime + delta
datetime.datetime(2022, 4, 1, 0, 0)
>>> adatetime = adafruit_datetime.datetime(*adate.timetuple()[:3])
>>> adatetime + delta
datetime.datetime(2022, 4, 1, 0, 0)

I've considered converting to Epoch, then adding seconds, then back to iso, but I am seeing an inability of the ESP32 to perform math against large numbers like epoch (eg. 1660233725 + 1), likely due to the number of bits required to store such a large number, approximation may be causing this behavior.

Yeah that happens with floats (which unfortunately .timestamp() is) not ints, due to floats being stored in 30 bits (and there is no support for double). Circuitpython supports long ints (of arbitrary length) - except on some SAMD21 boards.

ints: fine

>>> 1660233725 + 1
1660233726

floats: limited precision (around 6 digits)

>>> 1660233725. + 1
1.66023e+09
>>> (1660233725. + 1) - 1660233725.
0.0