30

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?

Frankline
  • 40,277
  • 8
  • 44
  • 75
David542
  • 104,438
  • 178
  • 489
  • 842
  • 1
    [Is link this useful?](http://stackoverflow.com/questions/10783864/django-1-4-timezone-now-vs-datetime-datetime-now) – helloV Nov 15 '14 at 19:52
  • Does this answer your question? [django 1.4 timezone.now() vs datetime.datetime.now()](https://stackoverflow.com/questions/10783864/django-1-4-timezone-now-vs-datetime-datetime-now) – ggorlen Nov 17 '21 at 17:41

3 Answers3

43

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

culix
  • 10,188
  • 6
  • 36
  • 52
dgel
  • 16,352
  • 8
  • 58
  • 75
4

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

  • Can you elaborate on what UTC support means? – Ren Dec 25 '19 at 16:59
  • 1
    From Django Documentation: Python’s datetime.datetime objects have a tzinfo attribute that can be used to store time zone information, represented as an instance of a subclass of datetime.tzinfo. When this attribute is set and describes an offset, a datetime object is aware. Otherwise, it’s naive. – eEmanuel Oviedo Jan 08 '20 at 12:20
  • 1
    "only timezone.now() have UTC support" means "only timezone.now() have tzinfo attribute" – eEmanuel Oviedo Jan 08 '20 at 12:22
2

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.

culix
  • 10,188
  • 6
  • 36
  • 52