Time Zones

Discover the methods for handling time zones within time series objects.

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 a TypeError.

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 return pytz 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 return pytz objects by default, therefore we need to prepend the 'dateutil/' string to return dateutil 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 the datetime.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 and dateutil.

For some time zones, pytz and dateutil 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.