Python Convert timezone with Pendulum

This Python Pendulum tutorial to show you how to convert date and time from one timezone to another timezone using the Pendulum package. Via different Python example programs we will learn how to convert date and time from UTC to another timezone, from one timezone to UTC, and convert date time between different timezone.

Table of contents

  1. Install Pendulum package
  2. Convert from a other timezone to UTC using convert() method
  3. Convert from UTC to another timezone using convert() method
  4. Convert DateTime to another timezone using in_timezone() method

Install Pendulum package

Installing the Pendulum package using the below command.

pip install pendulum

Convert from a other timezone to UTC using convert() method

The following Python program we use the FixedTimezone.convert() method to convert a DateTime instance from Melbourne timezone to UTC timezone.

import pendulum

melbourne_timezone = pendulum.timezone('Australia/Melbourne')
melbourne_datetime = pendulum.datetime(2021, 11, 20, 10, 20, 30, tz=melbourne_timezone)

utc_timezone = pendulum.timezone('UTC')

# Convert Melbourne Datetime to UTC DateTime
utc_datetime = utc_timezone.convert(melbourne_datetime)

print('Melbournce date time: ' + melbourne_datetime.to_datetime_string())
print('UTC date time: ' + utc_datetime.to_datetime_string())
The program output.
Melbournce date time: 2021-11-20 10:20:30
UTC date time: 2021-11-19 23:20:30

Convert from UTC to another timezone using convert() method

The following Python program we use the FixedTimezone.convert() method to convert a DateTime instance from UTC timezone to Tokyo timezone.

import pendulum

# Current date time in UTC
utc_now = pendulum.now(tz='UTC')

tokyo_timezone = pendulum.timezone('Asia/Tokyo')

# Convert UTC DateTime to Tokyo DateTime
tokyo_now = tokyo_timezone.convert(utc_now)

print('Tokyo date time now: ' + tokyo_now.to_datetime_string())
print('UTC date time now: ' + utc_now.to_datetime_string())
The program output.
Tokyo date time now: 2021-12-11 23:37:45
UTC date time now: 2021-12-11 14:37:45

Convert DateTime to another timezone using in_timezone() method

The following Python program we use Datetime.in_timezone() method to convert a DateTime instance from Sydney timezone to Paris timezone.

import pendulum

sydney_datetime = pendulum.datetime(2021, 11, 25, 9, 30, 0, tz = 'Australia/Sydney')

paris_datetime = sydney_datetime.in_timezone('Europe/Paris')

print('Sydney date time: ' + sydney_datetime.to_datetime_string())
print('Paris date time: ' + paris_datetime.to_datetime_string())
The program output.
Sydney date time: 2021-11-25 09:30:00
Paris date time: 2021-11-24 23:30:00

Happy Coding 😊