Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading