2

I have misunderstanding of how python's datetime works. Recently I saw two lines of code:

datetime.datetime.utcnow()
datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

And I actually can't understand what is the difference between them? In which situations those two objects behave in different way? I will be grateful for clarifying this question.

Artem Mezhenin
  • 5,539
  • 6
  • 32
  • 51

2 Answers2

4

The first creates a naive datetime object without a timezone, the second attaches a timezone object, making that object timezone aware.

Both objects will give you the date and time according to UTC.

Quoting from the datetime module documentation:

An aware object has sufficient knowledge of applicable algorithmic and political time adjustments, such as time zone and daylight saving time information, to locate itself relative to other aware objects. An aware object is used to represent a specific moment in time that is not open to interpretation [1].

A naive object does not contain enough information to unambiguously locate itself relative to other date/time objects. Whether a naive object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

Naive and aware objects are not comparable, nor can you perform datetime arithmetic between a naive and an aware datetime object.

Many operations on datetime.datetime objects differ between the two types; I recommend you search for 'naive' in the documentation. Where operations differ it is due to the extra timezone information present; for example, .utctimetuple() will return the same value as .timetuple() but with DST forced off for naive objects, but for an aware object the returned tuple represents UTC time whatever the timezone attached to the object was.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

This is used to assign timezones to the datetime objects. If you don't set the tzinfo you won't be able to set the timezone using datetime.astimezone

Also refer to: datetime.datetime.utcnow() why no tzinfo?

Community
  • 1
  • 1
Lucas Kauffman
  • 6,789
  • 15
  • 60
  • 86