jtr109
1/27/2018 - 3:22 AM

My Python Note

My Python Note

Datetime

Native and aware

Definition

There are two kinds of date and time objects: “naive” and “aware”.

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.

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.

How to check if the datetime is native or aware

a datetime object d is aware iff:

d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None

d is naive iff:

d.tzinfo is None or d.tzinfo.utcoffset(d) is None

How to Convert Them into Same Mode

the_time.replace(tzinfo=None)

Reference