micropython-lib icon indicating copy to clipboard operation
micropython-lib copied to clipboard

[lib: datetime] Updation of a `datetime` object with a `timedelta` obj reflects the change in the `datetime` object but is not reflected in the value returned by the `timetuple()` function

Open veethahavya-CU-cz opened this issue 1 year ago • 2 comments

--- MicroPython v1.23.0 on 2024-06-02; Raspberry Pi Pico with RP2040 --- -- Datetime library installed via mip (mpremote) so: mpremote mip install datetime

Discovery code:

>>> from datetime import datetime, timedelta
>>> from utime import time, localtime, mktime

>>> interval_s = 5 * 60
>>> intervals_passed_in_hr = total_seconds_this_hr // interval_s
>>> next_interval_seconds_in_hr = (intervals_passed_in_hr + 1) * interval_s
>>> seconds_to_next_interval = next_interval_seconds_in_hr - total_seconds_this_hr
>>> next_record_time_dt = now + timedelta(seconds=seconds_to_next_interval)

>>> now
datetime.datetime(2024, 8, 21, 14, 53, 39, 0, None, fold=0)
>>> next_record_time_dt
datetime.datetime(2024, 8, 21, 14, 55, 0, 0, None, fold=0)
>>> next_record_time_dt.timetuple()[:-2]
(2024, 8, 21, 14, 53, 52)

veethahavya-CU-cz avatar Aug 21 '24 14:08 veethahavya-CU-cz

I ran into this as well, annoying for porting existing code to use datetime. I can think of a few external fixes but they all seem hacky -- this should probably be fixed in the library itself.

I think this may have arisen because timetuple() tries to switch between gmtime and localtime, but on many boards, localtime doesn't have timezone info (and it's mostly patched out -- see https://github.com/micropython/micropython-lib/blob/master/python-stdlib/datetime/localtz.patch -- so I wonder if this was just missed while pulling that out...

NJAldwin avatar May 21 '25 16:05 NJAldwin

Hm, I am actually even seeing this for unrelated datetimes:

>>> timezone = datetime.timezone(offset = datetime.timedelta(hours = -4))
>>> timezone
UTC-04:00
>>> dt0 = datetime.datetime.now(tz = timezone)
>>> dt0
2025-05-21 14:57:44-04:00
>>> dt0.timetuple()
(2025, 5, 21, 18, 57, 4, 2, 141)
>>> dt1 = datetime.datetime.now(tz = timezone)
>>> dt1
2025-05-21 14:58:00-04:00
>>> dt1.timetuple()
(2025, 5, 21, 18, 57, 4, 2, 141)

this seems like a serious bug...

NJAldwin avatar May 21 '25 18:05 NJAldwin