close
The Wayback Machine - https://web.archive.org/web/20240710005833/https://www.geeksforgeeks.org/handling-timezone-in-python/
Open In App

Handling timezone in Python

Last Updated : 06 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

There are some standard libraries we can use for timezones, here we’ll use pytz. This library has a timezone class for handling arbitrary fixed offsets from UTC and timezones.

Installation

pytz is a third-party package that you have to install. To install pytz use the following command –

pip install pytz

Getting Started

After installation import the pytz package and now let’s see how we can pass in the timezones. Basic syntax in Python to get the date and time information is :

datetime.datetime.now()

The above syntax returns the current local date-time without any timezone information. But with the use of the pytz package we can handle this date-time information in the various timezones –now() gives us the option to pass in a time zone, so if you leave the time zone empty then it will also return the current local date-time. The output of now() depends upon the machine. The local time and time zone settings of the host machine will determine the output.

So in order to work with the timezone smoothly, it is recommended to use the UTC as your base timezone. To get the Universal Time Coordinated i.e. UTC time we just pass in the parameter to now() function. To get the UTC time we can directly use the ‘pytz.utc’ as a parameter to now() function as ‘now(pytz.utc)’. The offset will be shown at the end as (+ or – hours).

The below code shows the local time of the machine and the UTC time with offset.

Example:

Python3




import datetime
import pytz
  
dtObject_local = datetime.datetime.now()
dtObject_utc = datetime.datetime.now(pytz.utc)
  
print(dtObject_local)
print(dtObject_utc)


Output:

2021-05-28 12:19:56.962055

2021-05-28 06:49:56.962055+00:00

As you can see now we got the date time info of the local machine and in UTC, the timezone offset at the end is +00:00.

If we want to get date time info of specific timezone we just need to add the timezone in the parameter –

Syntax:

.now(pytz.timezone(‘ YOUR_TIMEZONE ‘))

The parameter pytz.timezone allows us to specify the timezone information as a string. We can pass in any available timezone and will get the current date time of that timezone, and it will also print the offset with respect to the UTC. i.e., the difference between UTC timezone(+00:00) and the specified time zone.

Example: 

Python3




import datetime
import pytz
  
dtObject_utc = datetime.datetime.now(pytz.utc)
  
dtObject_asia = datetime.datetime.now(pytz.timezone('Asia/Kolkata'))
dtObject_usc = datetime.datetime.now(pytz.timezone('US/Central'))
dtObject_turkey = datetime.datetime.now(pytz.timezone('Turkey'))
dtObject_eoslo = datetime.datetime.now(pytz.timezone('Europe/Oslo'))
dtObject_abelem = datetime.datetime.now(pytz.timezone('America/Belem'))
  
print(dtObject_utc)
  
print(dtObject_asia)
print(dtObject_usc)
print(dtObject_turkey)
print(dtObject_eoslo)
print(dtObject_abelem)


Output:

2021-05-28 23:12:56.559011+00:00

2021-05-29 04:42:58.027452+05:30

2021-05-28 18:12:58.072254-05:00

2021-05-29 02:12:58.092257+03:00

2021-05-29 01:12:58.107930+02:00

2021-05-28 20:12:58.109932-03:00

Here we got the different date time according to different timezones with offset. The offset will also show the (+/-) hours.  We can also convert any time zone to a different time zone.

Converting between Timezones

astimezone() method is used to manipulate i.e., to convert the datetime objects to the new specified datetime object. It uses an instance of the datetime object and returns new timezone information.

Syntax:

astimezone(pytz.timezone(‘ NEW_TIMEZONE ‘))

To get exactly what we need the following syntax will be followed.

Syntax :

dtObj = datetimeObject_instance.astimezone(pytz.timezone(‘ NEW_TIMEZONE ‘))

where,

  • dtObj : which stores the returned datetime object with newly created time date
  • datetimeObject_instance : currently available datetime object (i.e., reference to the local date time)
  • NEW_TIMEZONE : timezone information which should be changed to

Example:

Python3




import datetime
import pytz
  
# getting our local timezone
dtObject_local = datetime.datetime.now()
  
# converting local timezone to 'US/Central'
dtObject_usc = dtObject_local.astimezone(pytz.timezone('US/Central'))
  
# now converting 'US/Central' timezone to 'Pacific/Chuuk'
dtObject_pchuuk = dtObject_usc.astimezone(pytz.timezone('Pacific/Chuuk'))
  
print(dtObject_local)
print(dtObject_usc)
print(dtObject_pchuuk)


Output:

2021-05-29 04:46:26.288233

2021-05-28 18:16:26.288233-05:00

2021-05-29 09:16:26.288233+10:00

pytz has a large list of timezones available you can print them using the following method.

Example:

Python3




import pytz
  
for timeZone in pytz.all_timezones:
    print(timeZone)


Output:

Africa/Abidjan

Africa/Accra

Africa/Addis_Ababa

Africa/Algiers

Africa/Asmara

.

.

.

US/Samoa

UTC

Universal

W-SU

WET

Zulu



Similar Reads

Python | Timezone Conversion
Most datetime items came back from the dateutil parser are naive, which means they don't have an explicit tzinfo. tzinfo determines the timezone and UTC offset. It is the standard ISO format for UTC datetime strings. UTC is the coordinated universal time, and is fundamentally the equivalent as GMT. ISO is the International Standards Organization, w
3 min read
Get Current Time in different Timezone using Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world's standard for time zone. In order to get the current time of different time zones, we will be using the pyt
4 min read
Python time.timezone Constant
Python time. timezone constant returns the local (non-DST) timezone offset in UTC format, where DST stands for Daylight Saving Time. It is negative in most of Western Europe, positive in the US, zero in the UK). This constant returns the current timezone in which you reside. C/C++ Code import time print(time.timezone) Output: -19800time.tzname A si
1 min read
How to remove timezone information from DateTime object in Python
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone. In this article, we will discuss how to remove timezone information from the DateT
2 min read
How to make a timezone aware datetime object in Python
In this example, we are going to see how to make a timezone-aware DateTime object in Python. Timezone-aware objects are Python DateTime or time objects that include timezone information. An aware object represents a specific moment in time that is not open to interpretation. Checking if an object is timezone aware or not: We can easily check if a d
4 min read
Convert string to datetime in Python with timezone
Prerequisite: Datetime module In this article, we will learn how to get datetime object from time string using Python. To convert a time string into datetime object, datetime.strptime() function of datetime module is used. This function returns datetime object. Syntax : datetime.strptime(date_string, format) Parameters : date_string : Specified tim
3 min read
How to remove timezone from a Timestamp column in a Pandas Dataframe
The world is divided into 24 timezones. We all know that different timezones are required as the entire globe is not lit at the same time. While for many instances we might not require timezones especially in cases where the data resides on a common server present at some location or even our local systems. In this article, we are going to see how
3 min read
DateTime Timezone in SQLAlchemy
SQLAlchemy is a powerful and popular Python library that provides a flexible and efficient way to interact with databases. It uses the Object-Relational Mapping (ORM)tool, which acts as a bridge between the Python objects and the relational database. SQLALchemy provides a wide range of methods to work with databases, It provides a high level of abs
8 min read
Pandas Series dt.tz_convert | Change Timezone in DateTime Series
The dt.tz_convert() method converts tz-aware DateTime Series object from one time zone to another. Example C/C++ Code import pandas as pd sr = pd.Series(pd.date_range('2012-12-31 00:00', periods = 5, freq = 'D', tz = 'US / Central')) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx result = sr.dt.tz_convert(tz = 'Europe / Berlin')
2 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg