Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

python-dateutil returns "naive" datetime objects #1325

Open
mlasch opened this issue Nov 28, 2023 · 0 comments
Open

python-dateutil returns "naive" datetime objects #1325

mlasch opened this issue Nov 28, 2023 · 0 comments

Comments

@mlasch
Copy link

mlasch commented Nov 28, 2023

The Python datetime module from the standard lib supports so called "naive" and "time zone aware" datetime objects: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects

As far as I can see, dateutil returns in some (all?) cases naive datetime objects. Using naive objects is discouraged (is it?) and deprecated since version 3.12 (https://blog.miguelgrinberg.com/post/it-s-time-for-a-change-datetime-utcnow-is-now-deprecated).

Let's say, I want to compare the result from tzstr.transitions() I get a TypeError (Tested with Python3.10):

from datetime import datetime, timezone
import dateutil.tz

now = datetime.now(timezone.utc)  # recommended to replace utcnow()
posix_zone = dateutil.tz.tzstr("CET-1CEST,M3.5.0,M10.5.0/3")
start, end = posix_zone.transitions(2023)
now > start

Also the output of start.timestamp() will depend on the timezone the code is running.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[27], line 7
      5 posix_zone = dateutil.tz.tzstr("CET-1CEST,M3.5.0,M10.5.0/3")
      6 start, end = posix_zone.transitions(2023)
----> 7 now > start

TypeError: can't compare offset-naive and offset-aware datetimes

This makes sense, as I don't want to compare UTC times with a unspecified time. A workaround for me is to set UTC manually for the returned objects. I have to assume that the native datetime object represents UTC.

start = start.astimezone(timezone.utc)
end = end.astimezone(timezone.utc)

Should dateutil return time zone aware datetime objects, now that it looks like the naive type will be phased out sooner or later?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant