Python provides both builtin methods and external libraries for creating, modifying, parsing, and manipulating dates and times.
Basic datetime objects usage
The datetime module contains three primary types of objects - date, time, and datetime.
Arithmetic operations for these objects are only supported within same datatype and performing simple arithmetic with instances of different types will result in a TypeError.
Computing time differences
the timedelta module comes in handy to compute differences between times:
Specifying time is optional when creating a new datetime object
delta is of type timedelta
To get n day's after and n day's before date we could use :
n day's after date:
n day's before date:
Constructing timezone-aware datetimes
By default all datetime objects are naive. To make them timezone-aware, you must attach a tzinfo object, which provides the UTC offset and timezone abbreviation as a function of date and time.
Fixed Offset Time Zones
For time zones that are a fixed offset from UTC, in Python 3.2+, the datetime module provides the timezone class, a concrete implementation of tzinfo, which takes a timedelta and an (optional) name parameter:
For Python versions before 3.2, it is necessary to use a third party library, such as dateutil. dateutil provides an equivalent class, tzoffset, which (as of version 2.5.3) takes arguments of the form dateutil.tz.tzoffset(tzname, offset), where offset is specified in seconds:
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. pytz and dateutil are popular libraries providing time zone classes.
In addition to static time zones, dateutil provides time zone classes that use daylight savings time (see the documentation for the tz module). You can use the tz.gettz() method to get a time zone object, which can then be passed directly to the datetime constructor:
CAUTION: As of version 2.5.3, dateutil does not handle ambiguous datetimes correctly, and will always default to the later date. There is no way to construct an object with a dateutil timezone representing, for example 2015-11-01 1:30 EDT-4, since this is during a daylight savings time transition.
All edge cases are handled properly when using pytz, but pytz time zones should not be directly attached to time zones through the constructor. Instead, a pytz time zone should be attached using the time zone's localize method:
Be aware that if you perform datetime arithmetic on a pytz-aware time zone, you must either perform the calculations in UTC (if you want absolute elapsed time), or you must call normalize() on the result:
Converting timestamp to datetime
The datetime module can convert a POSIX timestamp to a ITC datetime object.
The Epoch is January 1st, 1970 midnight.
Fuzzy datetime parsing (extracting datetime out of a text)
It is possible to extract a date out of a text using the dateutil parser in a "fuzzy" mode, where components of the string not recognized as being part of a date are ignored.
dt is now a datetime object and you would see datetime.datetime(2047, 1, 1, 8, 21) printed.
Get an ISO 8601 timestamp
Without timezone, with microseconds
With timezone, with microseconds
With timezone, without microseconds
See ISO 8601 for more information about the ISO 8601 format.
Iterate over dates
Sometimes you want to iterate over a range of dates from a start date to some end date. You can do it using datetime library and timedelta object:
Parsing a string into a timezone aware datetime object
Python 3.2+ has support for %z format when parsing a string into a datetime object.
UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
For other versions of Python, you can use an external library such as dateutil, which makes parsing a string with timezone into a datetime object is quick.
The dt variable is now a datetime object with the following value:
Parsing a string with a short time zone name into a timezone aware datetime object
For dates formatted with short time zone names or abbreviations, which are generally ambiguous (e.g. CST, which could be Central Standard Time, China Standard Time, Cuba Standard Time, etc - more can be found here) or not necessarily available in a standard database, it is necessary to specify a mapping between time zone abbreviation and tzinfo object.
After running this:
It is worth noting that if using a pytz time zone with this method, it will not be properly localized:
This simply attaches the pytz time zone to the datetime:
If using this method, you should probably re-localize the naive portion of the datetime after parsing:
Parsing an arbitrary ISO 8601 timestamp with minimal libraries
Python has only limited support for parsing ISO 8601 timestamps. For strptime you need to know exactly what format it is in. As a complication the stringification of a datetime is an ISO 8601 timestamp, with space as a separator and 6 digit fraction:
but if the fraction is 0, no fractional part is output
But these 2 forms need a different format for strptime. Furthermore, strptime' does not support at all parsing minute timezones that have a:in it, thus2016-07-22 09:25:59+0300can be parsed, but the standard format2016-07-22 09:25:59+03:00` cannot.
There is a single-file library called iso8601 which properly parses ISO 8601 timestamps and only them.
It supports fractions and timezones, and the T separator all with a single function:
If no timezone is set, iso8601.parse_date defaults to UTC. The default zone can be changed with default_zone keyword argument. Notably, if this is None instead of the default, then those timestamps that do not have an explicit timezone are returned as naive datetimes instead:
Simple date arithmetic
Dates don't exist in isolation. It is common that you will need to find the amount of time between dates or determine what the date will be tomorrow. This can be accomplished using timedelta objects
This will produce results similar to:
Subtracting months from a date accurately
Using the calendar module
Using the dateutils module
Switching between time zones
To switch between time zones, you need datetime objects that are timezone-aware.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0