MySQL datetime not converting GMT to appropriate timezone in Python

I created A MySQL table with a timestamp field which is supposed to hold GMT time:

CREATE TABLE `Notes` (
  `RecordID` varchar(36) NOT NULL,
  `DateAdded` timestamp NOT NULL,  
  `UserID` varchar(36) NOT NULL, 
  `Note` text NOT NULL,
  PRIMARY KEY (`RecordID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SET FOREIGN_KEY_CHECKS = 1;

When I save a record, I use the following code to save the DateAdded:

gmt = pytz.timezone("GMT")        
return datetime.now(gmt)

It APPEARS to create the correct datetime in the Table; however, I am unable to convert the GMT datetime when I read the record back into Python:

local_tz = pytz.timezone("US/Pacific")
new_date = date.astimezone(local_tz) 

new_date is the same datetime in the table regardless of the timezone I set. Anything I should be looking at?

>Solution :

This works for me

local_tz = pytz.timezone(YOUR_TIMEZONE)


def normalized_local_now():  # use with tzinfo
    local_dt = datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt)


# get datetime depends on timezone
def datetime_local_now():  # usable for peewee datetimefield
    return normalized_local_now().replace(tzinfo=None)  # return datetime instance

Leave a Reply