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.
source share