tortoise / tortoise-orm

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

auto_now and auto_now_add to use local timezone #458

Open mojimi opened 4 years ago

mojimi commented 4 years ago

Hello, my team just ended up realizing that one of our bugs was due to tortoise using UTC time on auto_now and auto_now_add.

Could the timezone it uses be configurable or maybe just use the local server time?

Thanks

long2ice commented 4 years ago

Now it get current time from datetime.datetime.utcnow(), see https://github.com/tortoise/tortoise-orm/blob/develop/tortoise/fields/data.py#L310

mojimi commented 4 years ago

Now it get current time from datetime.datetime.utcnow(), see https://github.com/tortoise/tortoise-orm/blob/develop/tortoise/fields/data.py#L310

Yes! I'm aware, but utcnow() does not return the server time, it specifically returns UTC time

maxim-s-barabash commented 4 years ago

@mojimi, I recommend storing datetime in the database always in UTC, and lead to local time in the application and even better on the client-application. IMHO current implementation is correct

sunshineinwater commented 4 years ago

数据库存时间最好就是存utc时间,不然多端调用时候很容易出意想不到的bug

fangaofeng commented 4 years ago

但是数据库是支持timezone的,此时应该符合数据库格式。比如postgresql的datatime可以选择是否timezone,这个timezone会记录对应的时区。

fangaofeng commented 4 years ago

django reffer: DateField.auto_now¶ Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.

The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.

DateField.auto_now_add¶ Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:

For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now()