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

2020-06-09 02:14发布

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?

3条回答
手持菜刀,她持情操
2楼-- · 2020-06-09 02:28

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

查看更多
别忘想泡老子
3楼-- · 2020-06-09 02:44

If you want to use UTC, and you're using Python 3.2 or higher, this answer says you can do:

import datetime
datetime.datetime.now(datetime.timezone.utc)

This will give you a timezone-aware UTC datetime.

查看更多
相关推荐>>
4楼-- · 2020-06-09 02:50

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.

Read more about Django timezones

查看更多
登录 后发表回答