Repository navigation
Closed
Labels
questionFurther information is requested
Description
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn't find it.
- I searched the SQLModel documentation, with the integrated search.
- I already searched in Google "How to X in SQLModel" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to SQLModel but to Pydantic.
- I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
- I commit to help with one of those options 👆
Example Code
class UserBase(SQLModel):
username: str = Field(index=True, unique=True)
email: EmailStr = Field(unique=True, index=True) # this field should be unique for table and this field is required
fullname: str | None = None
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)Description
I write my created_at and updated_at fields like this, however, this did not work, because of the time awareness,
SQLModel user: fullname='string' created_at=datetime.datetime(2023, 1, 26, 18, 19, 32, 961000, tzinfo=datetime.timezone.utc) updated_at=datetime.datetime(2023, 1, 26, 18, 19, 32, 961000, tzinfo=datetime.timezone.utc) id=None is_staff=False is_admin=False username='string' email='[email protected]' password='string'
(sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.DataError'>: invalid input for query argument $4: datetime.datetime(2023, 1, 26, 18, 19, 3... (can't subtract offset-naive and offset-aware datetimes)
After checking Github, i found this solution:
class AuthUser(sqlmodel.SQLModel, table=True):
__tablename__ = 'auth_user'
id: Optional[int] = sqlmodel.Field(default=None, primary_key=True)
password: str = sqlmodel.Field(max_length=128)
last_login: datetime.datetime = Field(sa_column=sa.Column(sa.DateTime(timezone=True), nullable=False))It is written with mixing SQLModel stuff and the SALAlchemy, I know SQLModel is SQLAlchemy under the hood but this feels strange, cause i want to face SQLModel ONLY.
Is there any better way of handling this?
Let's say when SQLModel create tables, it will check the payding field created_at, if it is timezone aware datetime then it will set it as sa_column=sa.Column(sa.DateTime(timezone=True) so that we do not need to mix them both,
Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.10.2
Additional Context
No response
Reacted by Ömer Furkan İşleyen, AK, Roman Zydyk, Harsh Trivedi, Mike Shultz, Jim, Vadim Barsukov, Gustavo Argote, Stéphane Rabenarisoa, David and 5 more
Metadata
Metadata
Assignees
Labels
questionFurther information is requested
Activity
[-]Isn't there any better way to write timezone aware datetime field without using the SQLAlchemy ?[/-][+]Dose there any better way to write timezone aware datetime field without using the SQLAlchemy ?[/+]antont commentedon Feb 18, 2023
Generally you can't do this kind of things with SQLModel without using SA api directly, so I'd just drop that want.
enchance commentedon Oct 31, 2023
Coming from Tortoise ORM moving to SQLModel it would be great to have if the timezone would be saved without having to use SQLAlchemy directly. The project is new so I hope updates could be made soon.
antont commentedon Oct 31, 2023
New release has
so maybe this could be extended somehow to allow arguments for the sa Column type too.
Jufik commentedon Oct 27, 2024
That's how I sort this out now:
Indeed @antont , I believe adding
sa_type_kwargswould be really helpful.For such a widespread issue (eg: TZ Management): handle
pydantic_typescasting seems reasonnable.That will throw an error:
while that works:
Just considering all the
whatever_atkind of fields you'd get that seems like a reasonable thing to have.In the end, most of Pydantic Data Types are around date/datetime, and we could have:
as well as an updated
get_sqlalchemy_type, JSON/JSONValue would be left to tackle but YAGNI I guess.Taking a step back, I believe the this kind of challenges quite common, and making type-mapping used in
get_sqlalchemy_typepart of the public API would help a LOT.In the end one could:
get_sqlalchemy_type.register(annotation_type: Any,sa_type:Union[Type[TypeEngine],TypeEngine])and let SQLModel map that transparently.Obviously the Mapping should be Immutable, there are couple of guard rails to be put here and there but nothing impossible.
That can make
SQLModelfeel a bit like "magic" if mapping are added randomly on a code base yet that'd be really helpful.I can dig into contributing to this, yet I'd like to know if there any kind of interest for such a contrib'?
ekalosak commentedon Feb 26, 2025
@Jufik yes there's interest - your solution works, if you can make the ergonomics more natural, this would be an improvement. Congruity with Pydantic directly supports the first three project objectives:
^ excerpted from: https://sqlmodel.tiangolo.com/
My 2¢ on the issue: using
pydantic.AwareDatetimeshould "just work":navneet commentedon Jun 9, 2025
I scoured the internet to find this post! For anyone else struggling with timezone aware datetime columns, I found this to be most effective.
created_at: datetime = Field(sa_type=DateTime(timezone=True))OR
created_at: datetime = Field( default_factory=lambda: datetime.now(timezone.utc), sa_type=DateTime(timezone=True), nullable=False, )enchance commentedon Jun 14, 2025
I've been using these for a while now. Here the timezone is preserved and any latency is excluded since the value is generated by the db and not the app.
If you prefer to add the field manually for every table:
Your dates will be saved as
2025-06-13 10:45:43.129058 +00:00with the timezone.If you prefer to extend them which is what I recommend:
The need for
@declared_attris necessary here since they are meant to be used as mixins.Use it like so:
Personally, I created this instead to make things easier:
then use it as
antoniorodr commentedon Jul 16, 2025
I will try to implement your second implementation. But I've a question. How do you define the column name?
I want to have a "date" column in one of my tables. I don't really care about the time, only the date itself.
Thanks!
enchance commentedon Jul 16, 2025
The column name would be the name of the method you choose.
antoniorodr commentedon Jul 16, 2025
Thank you so much @enchance !
iloveitaly commentedon Aug 29, 2025
I have a mixin here that adds creatd_at and updated_at: https://github.com/iloveitaly/activemodel/blob/master/activemodel/mixins/timestamps.py
xXMrNidaXx commentedon Feb 25, 2026
Timezone-aware datetime without raw SQLAlchemy is doable!
Option 1 - Field with sa_column:
Option 2 - Custom type:
Option 3 - Pydantic validator:
The key is using
DateTime(timezone=True)in the sa_column.