Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 998
David542 Avatar asked Nov 15 '14 19:11

David542


People also ask

What timezone does datetime NOW () use?

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).

What does timezone NOW () return?

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 .

Is datetime datetime NOW () UTC?

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.

What is difference between datetime now and datetime UtcNow?

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.


2 Answers

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

like image 102
dgel Avatar answered Oct 03 '22 06:10

dgel


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

like image 40
eEmanuel Oviedo Avatar answered Oct 03 '22 06:10

eEmanuel Oviedo