tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.68k stars 390 forks source link

Datetime issue #1442

Closed dinosaurtirex closed 1 year ago

dinosaurtirex commented 1 year ago

Describe the bug Timezone not working

To Reproduce


TIMEZONE = pytz.timezone("Europe/Moscow")

models.py: 

class Afk(Model):

    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=128)
    deadline = fields.DatetimeField(null=True, auto_now=False)
    added_at = fields.DatetimeField(auto_now_add=True)

DB Config:
TORTOISE_ORM = {
    "connections": {"default": DB_URL},
    "apps": {
        "models": {
            "models": [
                "aerich.models",
                "auth_blueprint.models",
                "user_blueprint.models",
                "subscription_blueprint.models",
                "card_blueprint.models"
            ],
            "default_connection": "default",
            "maxsize": 50
        }
    }
}

Bug:
deadline = datetime.strptime(
    str(request.form.get("deadline")), 
    "%Y-%m-%d %H:%M:%S"
)
datetime_object_with_timezone = TIMEZONE.localize(deadline)
print(datetime_object_with_timezone)
await Card.filter(id=card_id).update(
    name=request.form.get("name"),
    deadline=datetime_object_with_timezone
)
card = await self.get_card_by_id(card_id)
print(card.deadline)

Expected behavior

2023-08-08 15:00:00+03:00
2023-08-08 12:00:00+00:00

Additional context Cant figure out whats wrong with datetime, it always return UTC DB Creation script:

CREATE USER usera WITH PASSWORD 'dfsfsdfsdfdsf';
CREATE DATABASE mydb;
ALTER DATABASE mydbSET timezone TO 'Europe/Moscow';

ALTER ROLE usera SET client_encoding TO 'utf8';
ALTER ROLE usera SET default_transaction_isolation TO 'read committed';
ALTER ROLE usera SET timezone TO 'Europe/Moscow';

GRANT ALL PRIVILEGES ON DATABASE crm_db TO crm_admin;
GRANT ALL ON DATABASE mydb TO usera ;
ALTER DATABASE mydb OWNER TO usera ;
dinosaurtirex commented 1 year ago

To fix that issue you need to simply add this to tortoise orm config file:

"use_tz": False,
"timezone": "Europe/Moscow",