Handling timezone in Python


A timezone is a geographic area where all the clocks are set to the same standard time, but owing to political choices, historical time zone changes, disparities in daylight saving time, and other factors, various locations may have distinct time offsets. A collection of classes for working with dates, times, and timezones are provided by the Python datetime module and pytz library, respectively. Timezone management in software development is crucial since it affects how accurately programmes provide results. With the help of three annotated examples, this article will examine how to manage timezones in Python using the datetime and pytz modules.

Installation

Python's datetime and pytz modules must be used in order to operate with timezones. The timezone functionality is provided by the pytz library, a third-party package, while the datetime module offers classes for working with dates and times.

pip install pytz
pip install datetime
  • The datetime module provides several classes for working with dates and times. The primary classes are date,tzinfo, timedelta, time and datetime.

  • The datetime class represents a specific date and time and has several attributes, including year, month, day, hour, minute, second, and microsecond.

  • A number of methods for handling datetime objects are also available in the datetime class. We may modify one or more characteristics of a datetime object while leaving the others unaffected by using the replace() function

  • Datetime objects can be formatted as strings in a specified way using the strftime() function.

Syntax

The pytz library's timezone() function may be used to set the timezone in Python. The datetime module can utilize the timezone object that is returned by the timezone() function, which accepts a string specifying the timezone's name. For instance, we may use the following code to set the time zone to "US/Eastern" −

import pytz
from datetime import datetime
eastern = pytz.timezone('US/Eastern')
dt = datetime.now(eastern)

However, the datetime class does not provide built-in support for timezones. That's where the pytz library comes in. The pytz module provides the timezone class, which represents a timezone object. A timezone object contains information about the timezone offset, daylight saving time rules, and timezone name.

The pytz module also provides several functions for working with timezones, including localize() and normalize(). The localize() function is used to set the timezone for a datetime object, while the normalize() function is used to convert a datetime object from one timezone to another.

Algorithm

  • Create datetime object to show time in a timezone

  • Use localize() function to set timezone

  • Change timezone with astimezone() function

  • Convert datetime object to string with strftime() function in a specific timezone

Setting the Timezone

Make use the pytz.timezone() function to create a timezone object and assign it to a variable

Example

import pytz
from datetime import datetime

# Create a timezone object for US/Eastern
eastern_tz = pytz.timezone('US/Eastern')
now = datetime.now()
now_eastern = eastern_tz.localize(now)
print(now_eastern)

Output

2023-04-17 16:58:31.317459-04:00

Create a timezone object for US/Eastern using pytz.timezone(), create a datetime object for the current time using datetime.now(), and then set the timezone for the datetime object using the localize() method of the timezone object.

Converting Time Between Time Zones

Using datetime and pytz, we can use the astimezone() method of the datetime object.

Example

import pytz
from datetime import datetime

# Create a timezone object for US/Eastern
eastern_tz = pytz.timezone('US/Eastern')
now = datetime.now()
now_eastern = eastern_tz.localize(now)

# Convert the datetime object to Pacific timezone
pacific_tz = pytz.timezone('US/Pacific')
now_pacific = now_eastern.astimezone(pacific_tz)
print(now_pacific)

Output

2023-04-17 13:58:41.599015-07:00

Using pytz, make a timezone object for US/Eastern. Create a datetime object for the current time by calling timezone(). use the localise() function of the timezone object to set the datetime object's timezone after calling now().

Instantiate another timezone object for the US/Pacific using pytz.timezone(), and use the astimezone() method of the datetime object to convert the datetime object to the Pacific time zone.

Formatting Time with Timezone

Formatting becomes easier with the strftime() method of the datetime object.

Example

import pytz
from datetime import datetime

# Create a timezone object for US/Eastern
eastern_tz = pytz.timezone('US/Eastern')
now = datetime.now()
now_eastern = eastern_tz.localize(now)

# Add formatting
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
now_str = now_eastern.strftime(fmt)
print(now_str)

Output

2023-04-17 16:59:06 EDT-0400

Use the strftime() function of the datetime object. The format string '%Y-%m- %d%H:%M:%S%Z%z' gives the year, month, day, hour, minute, and second, as well as the timezone abbreviation and timezone offset.

Conclusion

This article covers the core concepts and practices for handling timezones in Python. An explanation of how timezones work in the development of software follows the discussion of timezones' importance in programming. The required libraries and packages, including pytz and datetime, are then discussed along with installation instructions. After that, it goes into how timezones work in Python, including setting them, converting time between them, and formatting time using time zones. Finally, it provides sample code for each of these tasks along with guidance on how to address common Python timezone issues.

Updated on: 18-Apr-2023

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements