How To Use Dates And Times In Python
There are many ways of representing and manipulating dates and times in Python.
The Inbuilt datetime Module
Python comes with a built-in module suitable for common and basic datetime use cases. Somewhat confusingly, datetime
is both the name of the module and a name of one of the classes in the module, so if you want to use the datetime
class, you’ll see something like this:
from datetime import datetime
To create a datetime
object and store the current time you can use the .now()
function:
Note that a datetime
object stores both the date and the time (hence the name). The time is printed with a default resolution of 1us
(note that this is not it’s accuracy, only the resolution).
You can create a datetime
object representing an arbitrary time using the constructor which takes in the year, month, day and optional hour, minute, second and microsecond:
When you only provide the date and not the time, the time will default to 00:00:00.000000
:
Time Zones and the tzinfo Attribute
Date and time objects from the datetime
module fall into two categories, they can either be naive
or aware
.
naive
: The object is not aware of the time zone it is in. It is up to the programmer to remember the time zone and apply applicable transformations to the dates and times when needed.aware
: The object is aware of the time zone it is in.
Most basic uses of the datetime
module will end up creating a naive
object (which is fine if you only run the program in one time zone and don’t need to interact with other time zones). However, most of the objects have an optional tzinfo
attribute (which stands for time zone info) which when not None
, capture information about the time zone that the datetime is in.
If you want more information on naive
and aware
objects, see Determining If An Object Is Aware Or Naive in the official Python docs.
strftime()
strftime()
converts a datetime
object into a string representation of the datetime
, based on a format you specify.
strptime()
strptime()
converts a string into a datetime
object. It takes two mandatory parameters, the first is the date and time as a string, the second describes the format of the date and time (the first param) so strptime()
knows how to parse it (the format uses the same syntax as strftime()
).
Since Python 3.7, you also have the option to use the %z
specifier, which allows you to parse strings in ISO 8601 format:
Astropy’s time Module
Astropy has a powerful time
module which provides functionality over and above the datetime
module that is bundled with Python.
The first time you import astropy.time
, it will download leap second information.
Astropy’s time module provides support for operating on “arrays” of times. It does this by building in array support to the Time
class:
Subtracting two Astropy Time
objects gives you a TimeDelta
object (i.e. a duration):
See the Astropy Time and Dates documentation for more information.