Datetime is the name of one of the module within python and one of the other classes within the module. It is an instance that represents a single point in time. import datetime datetime.datetime.now() Output: datetime.datetime(2019, 10, 30, 19, 9, 31, 900482) Formatting datetime objectsHere we will learn about extracting attributes and writing different formats of date. d = datetime.datetime(2019, 10, 30, 20, 15) d.strftime("%Y/%m/%d") > '2019/10/30' d.strftime("%d %b %y") > '30 Oct 19' d.strftime("%Y-%m-%d %H:%M:%S") > '2019-10-30 20:15:00' Naive v/s Aware in PythonSo far, we have only seen formatting datetime objects. That means the object is naive to any sort of time zones. By default all Fixed Offset Time Zones For time zones that are a fixed offset from UTC, in Python 3.2+, the 0 and an (optional) name parameter:Python 3.x3.2
For Python versions before 3.2, it is necessary to use a third party library, such as 1. 1 provides an equivalent class, 3, which (as of version 2.5.3) takes arguments of the form 4, where 5 is specified in seconds:Python 3.x3.2 Python 2.x2.7
Zones with daylight savings time For zones with daylight savings time, python standard libraries do not provide a standard class, so it is necessary to use a third party library. 6 and 1 are popular libraries providing time zone classes.In addition to static time zones, 1 provides time zone classes that use daylight savings time (see the documentation for the 9 module). You can use the 0 method to get a time zone object, which can then be passed directly to the datetime constructor:
CAUTION: As of version 2.5.3, 1 does not handle ambiguous datetimes correctly, and will always default to the later date. There is no way to construct an object with a 1 timezone representing, for example 4, since this is during a daylight savings time transition.All edge cases are handled properly when using 6, but 6 time zones should not be directly attached to time zones through the constructor. Instead, a 6 time zone should be attached using the time zone's 8 method:
Be aware that if you perform datetime arithmetic on a 6-aware time zone, you must either perform the calculations in UTC (if you want absolute elapsed time), or you must call 0 on the result: |