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?
In the documentation, it can also be seen that, since Python 3.6, datetime. now() can be called without any arguments and return the correct local result (naive datetime s are presumed to be in the local time zone).
timezone. now() useful. This function returns the current date and time as a naive datetime when USE_TZ = False and as an aware datetime when USE_TZ = True .
Getting the UTC timestampUse the datetime. datetime. now() to get the current date and time. Then use tzinfo class to convert our datetime to UTC.
UtcNow tells you the date and time as it would be in Coordinated Universal Time, which is also called the Greenwich Mean Time time zone - basically like it would be if you were in London England, but not during the summer. DateTime. Now gives the date and time as it would appear to someone in your current locale.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With