Time Zones
Discover the methods for handling time zones within time series objects.
We'll cover the following
Introduction
Time zones play a significant role in time series data analysis, because businesses often span multiple regions with different time zones. Understanding time zones is important for the correct interpretation and alignment of data. For instance, comparing stock market data from various areas without considering time zones may result in inaccurate insights.
Time zone conversions
The pandas
library's objects are timezone-unaware by default, meaning they aren’t assigned to any specific time zone. To set a time zone for time series objects, we can utilize either of the following two commonly-used ways:
Use the
tz
keyword argument when creating time series objects with classes (Timestamp
,DatetimeIndex
) or methods (e.g.,date_range()
).Use the
tz_localize()
method.
Note: If a time series object already has a time zone assigned, using
tz_localize()
will raise aTypeError
.
There are also three common ways to specify the time zone, using either the pytz
or the dateutil
library. For each of these two ways, we can specify it as a time zone object or as a string:
pytz
:As a time zone object, e.g.,
pytz.timezone('Australia/Victoria')
.As a string, e.g.,
'Australia/Victoria'
. These string values are technically known as Olson time zone strings, and they returnpytz
time zone objects by default.
dateutil
:As a time zone object, e.g.,
dateutil.tz.gettz('Australia/Victoria')
.As a string, e.g.,
'dateutil/Australia/Victoria'
. The Olson time zone strings returnpytz
objects by default, therefore we need to prepend the'dateutil/'
string to returndateutil
time zone objects instead.
Note: There is a third way to specify the time zone, which is using the
datetime.timezone
objects. For example, we can use thedatetime.timezone.utc
to specify a time zone corresponding to the Coordinated Universal Time (UTC). However, to simplify the content in this lesson, we focus on the two most commonly used ways instead, i.e.,pytz
anddateutil
.For some time zones,
pytz
anddateutil
have different definitions of the zone. However, more often than not, there is no need to worry because this is typically not a problem for commonly-used time zones, such as US/Eastern.
Let’s look at a few examples to understand this concept better. For instance, the following code shows how to utilize the tz
keyword in date_range()
to generate a date range that is assigned the Singapore time zone with pytz
:
Get hands-on with 1200+ tech skills courses.