tortoise / tortoise/tortoise-orm
An offset-aware datetime makes a crash (postgresql)
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Describe the bug
I think that tortoise-postgresql can't handle datetime object with timezone (as known as offset-aware datetime)
To Reproduce
import asyncio
from datetime import datetime
import pytz
from tortoise import Tortoise, fields
from tortoise.models import Model
class Test(Model):
date = fields.DatetimeField()
async def main():
await Tortoise.init(
db_url="postgres://postgres:pass@db.host:5432/somedb",
modules={"models": ["__main__"]},
)
await Tortoise.generate_schemas()
# It works! (offset-naive datetime)
# await Test(date=datetime.utcnow()).save()
# But it makes error. (offset-aware datetime)
await Test(date=datetime.now(pytz.UTC)).save()
await Tortoise.close_connections()
asyncio.run(main())
stack info
....
await Test(date=datetime.now(timezone.utc)).save()
File ".../python3.8/site-packages/tortoise/models.py", line 896, in save
await executor.execute_insert(self)
File ".../python3.8/site-packages/tortoise/backends/base/executor.py", line 160, in execute_insert
insert_result = await self.db.execute_insert(self.insert_query, values)
File ".../python3.8/site-packages/tortoise/backends/asyncpg/client.py", line 38, in translate_exceptions_
raise OperationalError(exc)
tortoise.exceptions.OperationalError: invalid input for query argument $1: datetime.datetime(2020, 7, 22, 16, 32, 4... (can't subtract offset-naive and offset-aware datetimes)
Expected behavior
It should work! even in the case of offset-aware
Additional context
Offset-aware datetime uses utc+0 timestamp to calculate timedelta or something. So it works same with offset-naive(without timezone), but it more safe and easier to debug.
Do you have plans about timezone support? fields.DatetimeField and some kind of that don't have timezone options.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the supplied PostgreSQL reproduction first, then inspect fields.DatetimeField and the asyncpg path at tortoise/backends/asyncpg/client.py. Compare the offset-naive and offset-aware saves, and use the expected behavior and timezone-support question to define completion: an offset-aware datetime should save without the reported OperationalError, with its timezone behavior decided.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- postgresql, python
- Domain
- databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100