Display The Time In A Different Time Zone

Summary: You are recommended to use the pytz library because of its efficiency and effectiveness in displaying time in a different time zone in Python. However, it would be best to understand the datetime module because it plays a massive role in date and time manipulation.

Introduction

Displaying the time in a different time zone can be hectic. Regions and nations frequently update their time zones. There are many time zones, making it impossible to cram all of them.

Another challenging part is choosing the right datetime method. For instance, when should you use datetime over timedelta or time zone over time? What is the best library to manipulate time zones in Python?

Although the standard python library comes with several ways to display the time in a different time zone, the pytz package is an awesome way because it is extremely efficient to use.

It would be beneficial to understand the datetime module before applying the pytz library because, at the end of the day, pytz manipulates datetime modules methods. Let’s get started.

Choose The Right Datetime Method

Datetime is the module for manipulating time in Python. You need to import it from the main library before working with time and date schedules.

import datetime

You can either use naive or aware datetime. Naive datetime does not accommodate time zones in the output. Apply it when you need simplicity without much detail. Otherwise, use aware datetimes.

Displaying the time in a different time zone is possible via aware date and time. However, since aware datetimes are extended versions of the naive, it would help to understand naive datetimes first. Let’s do that right away.

The three typical naive datetime instances are date, time, and datetime. They accept parameters, but the methods on them, such as today(), now(), and utcnow(), do not receive parameters. Here are their practical examples.

➀ datetime.date

The date method accepts Year, Month and Day as inputs.

import datetime
# create date from a method: (10th March 2022)
t_day = datetime.date(2022, 4, 10)
print(t_day)
# create date from a constructor
today_date = datetime.date.today()
print(today_date)

Output:

2022-04-10
2022-03-12

Caution: Do not precede the input elements with a zero. For example, entering 03 instead of 3 raises a syntax error.

You can find more information about the time using certain attributes. For example,

print(t_day.year)
print(t_day.today())
print(t_day.weekday())

➀ datetime.time

datetime.time shows the time in Hours, Minutes, Seconds and Milliseconds.

Although datetime.time is a naive way to express time, you can use its tz or tzinfo options to include time zones.

import datetime as dt

tz_string = dt.datetime.now(dt.timezone.utc).astimezone().tzname()
t_time = dt.datetime.now()
print(tz_string)
print(t_time)

time_zone_name = dt.datetime.now(dt.timezone.utc).tzname()
utc_time = dt.datetime.now(dt.timezone.utc)
print(time_zone_name)
print(utc_time)

Output:

India Standard Time
2022-03-12 12:05:44.374148
UTC
2022-03-12 06:35:44.374148+00:00

➀ datetime.datetime

datetime.datetime shows time in Year, Month, Day, Hours, Minutes, Seconds and microseconds.

import datetime

# create time from a method: (9th March 2022 at 11 hours, 12 minutes, 30 seconds and 200 milliseconds)
full_time = datetime.datetime(2022, 4, 9, 11, 12, 30, 200)
print(full_time)
# create time from a constructor
t_today = datetime.datetime.today()  # current local datetime without a time zone.
print(t_today)
t_now = datetime.datetime.now()  # current local datetime with an option to pass in a time zone.
print(t_now)
t_utcnow = datetime.datetime.utcnow()  # current utc time with the tzinfo set to none.
print(t_utcnow)

Output:

2022-04-09 11:12:30.000200
2022-03-12 12:25:27.201673
2022-03-12 12:25:27.201673
2022-03-12 06:55:27.201673

You can also get a portion of the result using methods like date() and time().

date_portion = full_time.date()
time_portion = full_time.time()

datetime.date and datetime.datetime work closely with time deltas. A timedelta is the difference between two dates or time. It helps determine the previous or future dates and time.

Assume you want to know the date in 3 days from a specified time. You can do that using the timedelta method as follows.

import datetime

# get today's date and full time
tday = datetime.date(2022, 3, 10)
full_time = datetime.datetime(2022, 4, 9, 11, 12, 30, 200)

# instantiate a 3-day countdown
time_delta = datetime.timedelta(days=3)

# add today's date/time to timedelta then print the result
print(tday + time_delta)
print(full_time + time_delta)

# subtract the timedelta from today's date/time then print the result
print(tday - time_delta)
print(full_time - time_delta)

You should get an output closer to the following.

2022-03-13
2022-04-12 11:12:30.000200
2022-03-07
2022-04-06 11:12:30.000200

Now that you understand the datetime methods to operate with the pytz module, let’s display the time in a target time zone.

Recommended Read: How to Get the Current Time in Python?

Display The time In A Different Time Zone In 3 Steps Using pytz

Step 1: Install the pytz library

Head over to your terminal and install the pytz library.

pip install pytz

then import it.

import pytz

Step 2: Get the current UTC and make it time zone aware

It is recommended to use the UTC zones when dealing with pytz. With the UTC attribute, we can make the naive dates and time to be aware of the time zone.

tz_aware_dt = datetime.datetime(2022, 4, 9, 11, 12, 30, 200, tzinfo=pytz.UTC)

# print the result
print(tz_aware_dt)

You get an output similar to this when you print tz_aware_dt.

2022-04-09 11:12:30.000200+00:00

The +00:00 part represents the UTC offset. From there, you can get the aware zone using either now() or utcnow() methods.

The difference between now() and utcnow() is that now() accepts time zone as a parameter, while utcnow() does not. However, you can still make it collect inputs using the replace() method.

# using now()
tz_now = datetime.datetime.now(tz=pytz.UTC)
# using utcnow()
tz_utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)

# print the result
print(tz_now)
print(tz_utcnow)

Step 3: Convert the UTC to a different time zone

Let’s convert the tz_now time into a different time zone.

First, identify the target time zone from the pytz library.

# get a list of all time zones.
for tz in pytz.all_timezones:
  print(tz)

# grab the target time zone from the list and store it as a string.
target_tz = "Asia/Dubai"

Second, pass the target time zone into the astimezone() method.

result = tz_now.astimezone(pytz.timezone(target_tz))

# print the result
print(result)

And voila, you can display the time in your target time zone!

You can now format the result using the strftime method. For example, instead of outputting,

2022-03-11 22:46:40.838214+04:00

you can display

The time in Asia/Dubai is 23:19:38

by printing the result as follows.

# print the result
print(f"\nThe time in {target_tz} is {result.strftime('%H:%M:%S')}")

Conclusion

Well, that was it for this article. We have unearthed numerous capabilities of the datetime module and found out how we can use the pytz library to solve our purpose. Please feel free to drop in your doubts. Stay tuned and subscribe for more interesting discussions and tutorials.


Related Reads: