Astimezone () cannot be applied to a naive date

Are timezones () and datetimes possible for conflict with my OS in terms of time, etc.?

At first this is a stupid question, because I had this problem, and I can’t understand why and where this is happening.

Looking at this:

def parse_datetime(a_datetime, account): tz = pytz.timezone(account.timezone_name) return datetime.astimezone(parser.parse(a_datetime), tz) 

This function just needs to return a good datetime object like timezone (), just that! But not!

All I know is that I get this message: astimezone () cannot be applied to naive datetime ()

Since I have friends with the same function, and on their PC the code works well, but in my case it doesn’t work.

Esperants: There is something wrong with the configuration on your machine ... But, not sure.

If someone else comes across this and knows that he is just reading what is here, well, it would be nice if you told me, I would be glad. Thanks in advance!

+6
source share
1 answer

You are using the wrong method to bind the time zone to a datetime object.

As described on the pytz page, you want to call this method on a datetime object, not a class:

 def parse_datetime(a_datetime, account): tz = pytz.timezone(account.timezone_name) return parser.parse(a_datetime).astimezone(tz) 

This only works for already localized datetime objects (with, for example, UTC as the time zone).

As indicated in the same documentation, you better use the .localize() method for the timezone object:

 def parse_datetime(a_datetime, account): tz = pytz.timezone(account.timezone_name) return tz.localize(parser.parse(a_datetime)) 

This works with naive datetime objects and does the right thing for time zones with historical data.

If you have mixed data, some of them and some without time zones, then you should check if there is a time zone there:

 def parse_datetime(a_datetime, account): dt = parser.parse(a_datetime) if dt.tzinfo is None: tz = pytz.timezone(account.timezone_name) dt = tz.localize(dt) return dt 

Timestamps that already have a timezone binding will result in datetime objects that depend on the time zone and do not need to be reworked in another time zone.

+7
source

Source: https://habr.com/ru/post/957361/


All Articles