pythondjangopostgresqldatetimetimezone

Django + FactoryBoy -> Postgres not converting datetime to utc correctly


Okay, this is a weird one. I've got a Django model that I'm writing to Postgres via FactoryBoy for testing.

contract = ContractFactory(        
    effective_date=datetime.datetime(2023, 1, 1, tzinfo=pytz.timezone('US/Central'))
)

I'm in US/Central, and I expect the database to store the object in UTC. The datetime in Postgres should be 2023-01-01 06:00:00 UTC since the difference between timezones is 6 hours.

If I fetch the object back and print the date, it's wrong!

2023-01-01 05:51:00+00:00

If I fetch it from Postgres directly, it's also wrong:

2023-01-01 05:51:00.000000 +00:00

I checked the raw time in the database and it's correct. Postgres is running in a Docker container, and if I do a select now() the time is just fine in UTC.

Where could this be coming from?


Solution

  • Found the answer here: unexpected results converting timezones in python

    Using the datatime function to build the time doesn't work. It requires creation of the datetime and then localization after.