Timezone.now() vs datetime.datetime.now()

女生的网名这么多〃 提交于 2019-12-21 07:15:18

问题


When should I be using django's timezone.now() and when should I be using python's datetime.datetime.now().

For example, in the following INSERT which would make more sense?

- Product.objects.create(title='Soap', date_added=datetime.datetime.now())
- Product.objects.create(title='Soap', date_added=timezone.now())

Is there a rule of thumb on when to use each?


回答1:


Just always use timezone.now(). Django now has timezone support which requires timezone 'aware' datetime objects. datetime.now() will return a timezone naive object, whereas timezone.now() will return a timezone aware object.




回答2:


You can write in shell, for example:

timezone.datetime.now() < timezone.now() 

And the error message is:

TypeError: can't compare offset-naive and offset-aware datetimes

They are different objects, only timezone.now() have UTC support



来源:https://stackoverflow.com/questions/26949959/timezone-now-vs-datetime-datetime-now

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!