Right now there is no simple way to get a timezone-aware time for the current time in the current time zone [without resorting to outside libraries like pytz], I would like to propose a simple extension to datetime.now to allow returning an aware datetime object using a plain single-offset tzinfo object: datetime.now('auto') shall return a datetime using a simple offset-based timezone object.
[Incidentally, I also think that utcoffset() on naive timestamps should be able to return the offset that astimezone would use to convert the time. I only discovered it didn't while writing this proposal] some simplistic possible implementations: def utcoffset_naive(dt): ut = dt.astimezone(datetime.timezone.utc).replace(tzinfo=None) return dt - ut def now_auto(): now = datetime.datetime.now() return now.replace(tzinfo=datetime.tzinfo(utcoffset_naive(now)), fold=0) A better implementation though would be to capture tm_gmtoff, and perhaps also tm_zone for tzname, from localtime() inside _fromtimestamp. This could also bypass the fold detection stage because single-offset tzinfo objects have no folds. I am specifically *not* proposing the creation of a tzinfo class representing "just use the local time as-is", because the meaning of timestamps with such a tzinfo attached might change during the lifetime of a program when system settings and/or environment variables are changed. A tzinfo class that identifies a system-specific timezone might be viable, but on some systems may require setting global state such as environment variables before each conversion. Also, such a tzinfo object could simply be passed as-is to datetime.now, whereas my proposal is to automatically select from (typically) two different fixed-offset tzinfo objects that would be used for DST and non-DST timestamps. This could be accomplished with a tzinfo class whose fromutc method always returns a datetime with a fixed-offset tzinfo attached, but I don't know if this aspect of the tzinfo API [that fromutc may return a datetime with any timezone attached, or indeed any object] is documented or stable, or what the other consequences would be [e.g. what if such a tzinfo object is attached to a datetime directly using the constructor or replace]? A magic sentinel object such as the string 'auto' allows this functionality to be limited to now (and perhaps fromtimestamp) without the unintended consequences of a 'magical' tzinfo escaping into other parts of the API. _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/2AZBR3VIHSREDT353R5KLKASYH75N66V/ Code of Conduct: http://python.org/psf/codeofconduct/