Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to store all datetime as UTC instead of naive datetimes #118

Open
baptiste0928 opened this issue Mar 16, 2021 · 2 comments
Open

Option to store all datetime as UTC instead of naive datetimes #118

baptiste0928 opened this issue Mar 16, 2021 · 2 comments
Labels
enhancement New feature or request

Comments

@baptiste0928
Copy link

Feature request

Context

According to the documentation :

Only naive datetime objects will be allowed as MongoDB doesn't store the timezone information. Also, the microsecond information will be truncated.

Naive datetimes are relative to the configured timezone of the host running the program. This can lead to bugs when the database is used by multiple hosts where timezone configuration is inconsistent. An option to ensure that datetime are UTC datetimes before saving data, and to set timezone info to UTC when getting data from the db will prevent this kind of bugs.

Solution

The solution I think is best is to add an argument to the Field() function.

from datetime import datetime
from odmantic import Field, Model


class SomeModel(Model):
    date: datetime = Field(utc_datetime=True)

When saving instance, datetime.astimezone(tz=timezone.utc) should be used to ensure datetime is in UTC. When retrieving data from the database, datetime fields will became aware datetimes with timezone set to UTC. The timezone information will not be stored in MongoDB.

Alternative solutions

An alternative solution is to use naive datetimes in UTC (e.g. with datetime.utcnow()), but this need to adapt existing code, and convert aware datetimes to naive datetime when we want to save them to the database.

Additional context

If this feature request is accepted, I could do a PR 😃
Thank you in advance for your answers,

@ivan-gj
Copy link

ivan-gj commented Jan 29, 2023

Hi, @baptiste0928,
I took the liberty to propose a pull request (#325) that would solve this issue in a clean way, without breaking any API, and without the need to define any parameter in the Field part.

Please check it out and see if you like it!

@ivan-gj
Copy link

ivan-gj commented Jan 29, 2023

Hi again!
Stupid me, with the excitement of knowing how to fix this, I did not realise someone else already did!!

Pull requests #70 and #71 should solve this very same thing, + more customization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants