What I need to do
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this one legacy case.
What I’ve Tried
First, to demonstrate the problem:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> import pytz
>>> unaware = datetime.datetime(2011,8,15,8,15,12,0)
>>> unaware
datetime.datetime(2011, 8, 15, 8, 15, 12)
>>> aware = datetime.datetime(2011,8,15,8,15,12,0,pytz.UTC)
>>> aware
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> aware == unaware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
First, I tried astimezone:
>>> unaware.astimezone(pytz.UTC)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: astimezone() cannot be applied to a naive datetime
>>>
It’s not terribly surprising this failed, since it’s actually trying to do a conversion. Replace seemed like a better choice (as per How do I get a value of datetime.today() in Python that is «timezone aware»?):
>>> unaware.replace(tzinfo=pytz.UTC)
datetime.datetime(2011, 8, 15, 8, 15, 12, tzinfo=<UTC>)
>>> unaware == aware
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes
>>>
But as you can see, replace seems to set the tzinfo, but not make the object aware. I’m getting ready to fall back to doctoring the input string to have a timezone before parsing it (I’m using dateutil for parsing, if that matters), but that seems incredibly kludgy.
Also, I’ve tried this in both Python 2.6 and Python 2.7, with the same results.
Context
I am writing a parser for some data files. There is an old format I need to support where the date string does not have a timezone indicator. I’ve already fixed the data source, but I still need to support the legacy data format. A one time conversion of the legacy data is not an option for various business BS reasons. While in general, I do not like the idea of hard-coding a default timezone, in this case it seems like the best option. I know with reasonable confidence that all the legacy data in question is in UTC, so I’m prepared to accept the risk of defaulting to that in this case.
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module.
Getting a Datetime object
Method 1: Using now() method
A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/object of the datetime.datetime class. The now() method returns an object that represents the current date and time.
Python
import
datetime
print
(datetime.datetime.now())
Output:
2022-01-17 17:15:50.838373
Method 2: Defining the Datetime object manually
We can also declare the DateTime object manually
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
)
print
(obj)
Output:
2001-12-09 00:00:00
After this, we learn how to format our Datetime objects.
Formatting DateTime objects
Sometimes we need to print our datetime objects in different formats. For these operations, we are going to use strftime() method. The syntax of strftime() is:
Syntax : strftime(format)
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
)
print
(obj.strftime(
"%a %m %y"
))
print
(obj.strftime(
"%m-%d-%Y %T:%M%p"
))
Output:
Sun 12 01 12-09-2001 00:00:00:00AM
We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
,
12
,
11
,
23
)
print
(obj.hour)
print
(obj.minute)
print
(obj.second)
Output:
12 11 23
We can also get a datetime object using the strptime() method, in which we get a DateTime object from a string. Since the strings we use can be formatted in any form, we need to specify the expected format. To understand this, let’s look at the syntax of strptime():
Syntax : datetime.strptime(data,expected_format)
Parameters :
- data : Our time and date passed as a string in a particular format
- expected_format : the format in which data is presented in the first parameter
Python
import
datetime
print
(datetime.datetime.strptime(
"Jan 1, 2013 12:30 PM"
,
"%b %d, %Y %I:%M %p"
))
Output:
2013-01-01 12:30:00
Working with Timezones
The DateTime objects that we have been working with till now are what are known as naive DateTime objects. A naive DateTime object does not have any information on the timezone. We can check this using the tzinfo property.
Python
import
datetime
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
print
(obj.tzinfo)
Output:
None
To set our own timezones, we have to start using the pytz module. In the next example, we will create a DateTime object first and then create a timezone object. We will then localize that timezone object to the DateTime object and check the tzinfo property.
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
aware_obj
=
tz.localize(obj)
print
(aware_obj.tzinfo)
Output :
Asia/Kolkata
Conversion of DateTime object from one Timezone to another
To convert the DateTime object from one timezone to another we need to use the astimezone() method.
Syntax : DateTimeObject.astimezone(tz=None)
tz : The specified timezone to which the DateTimeObject needs to be converted to
Returns : a datetime instance according to the specified time zone parameter tz
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
obj
=
tz.localize(obj)
new_tz
=
pytz.timezone(
'America/New_York'
)
new_tz_time
=
obj.astimezone(new_tz)
print
(new_tz_time)
Output:
2001-11-14 14:50:25-05:00
Working with the timedelta class
We can check the difference between two DateTime objects with are either both localized to the same timezone or are naive. In the next example, we are going to create two DateTime objects localized to the same timezone and check their difference. The difference of the time returned should be an object of the timedelta class.
Python
import
datetime
import
pytz
obj1
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
obj2
=
datetime.datetime(
2001
,
6
,
3
,
2
,
10
,
12
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
obj1
=
tz.localize(obj1)
obj2
=
tz.localize(obj2)
print
(obj2
-
obj1)
print
(obj1
-
obj2)
print
(
type
(obj1
-
obj2))
Output :
-165 days, 0:49:47 164 days, 23:10:13 <class 'datetime.timedelta'>
Not just differences, timedelta objects can also be used for addition. If we add a timedelta object to a datetime object, we get another datetime object that has the timedelta factored in as the difference with the first datetime object. Let’s see the example :
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
diff
=
datetime.timedelta(days
=
90
, hours
=
1
)
new_obj
=
obj
+
diff
print
(new_obj)
Output:
2002-02-13 02:20:25
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module.
Getting a Datetime object
Method 1: Using now() method
A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/object of the datetime.datetime class. The now() method returns an object that represents the current date and time.
Python
import
datetime
print
(datetime.datetime.now())
Output:
2022-01-17 17:15:50.838373
Method 2: Defining the Datetime object manually
We can also declare the DateTime object manually
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
)
print
(obj)
Output:
2001-12-09 00:00:00
After this, we learn how to format our Datetime objects.
Formatting DateTime objects
Sometimes we need to print our datetime objects in different formats. For these operations, we are going to use strftime() method. The syntax of strftime() is:
Syntax : strftime(format)
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
)
print
(obj.strftime(
"%a %m %y"
))
print
(obj.strftime(
"%m-%d-%Y %T:%M%p"
))
Output:
Sun 12 01 12-09-2001 00:00:00:00AM
We can get different attributes of the datetime object. In the code below, we are going to get the hours, minutes, and seconds.
Python
import
datetime
obj
=
datetime.datetime(
2001
,
12
,
9
,
12
,
11
,
23
)
print
(obj.hour)
print
(obj.minute)
print
(obj.second)
Output:
12 11 23
We can also get a datetime object using the strptime() method, in which we get a DateTime object from a string. Since the strings we use can be formatted in any form, we need to specify the expected format. To understand this, let’s look at the syntax of strptime():
Syntax : datetime.strptime(data,expected_format)
Parameters :
- data : Our time and date passed as a string in a particular format
- expected_format : the format in which data is presented in the first parameter
Python
import
datetime
print
(datetime.datetime.strptime(
"Jan 1, 2013 12:30 PM"
,
"%b %d, %Y %I:%M %p"
))
Output:
2013-01-01 12:30:00
Working with Timezones
The DateTime objects that we have been working with till now are what are known as naive DateTime objects. A naive DateTime object does not have any information on the timezone. We can check this using the tzinfo property.
Python
import
datetime
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
print
(obj.tzinfo)
Output:
None
To set our own timezones, we have to start using the pytz module. In the next example, we will create a DateTime object first and then create a timezone object. We will then localize that timezone object to the DateTime object and check the tzinfo property.
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
aware_obj
=
tz.localize(obj)
print
(aware_obj.tzinfo)
Output :
Asia/Kolkata
Conversion of DateTime object from one Timezone to another
To convert the DateTime object from one timezone to another we need to use the astimezone() method.
Syntax : DateTimeObject.astimezone(tz=None)
tz : The specified timezone to which the DateTimeObject needs to be converted to
Returns : a datetime instance according to the specified time zone parameter tz
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
obj
=
tz.localize(obj)
new_tz
=
pytz.timezone(
'America/New_York'
)
new_tz_time
=
obj.astimezone(new_tz)
print
(new_tz_time)
Output:
2001-11-14 14:50:25-05:00
Working with the timedelta class
We can check the difference between two DateTime objects with are either both localized to the same timezone or are naive. In the next example, we are going to create two DateTime objects localized to the same timezone and check their difference. The difference of the time returned should be an object of the timedelta class.
Python
import
datetime
import
pytz
obj1
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
obj2
=
datetime.datetime(
2001
,
6
,
3
,
2
,
10
,
12
)
tz
=
pytz.timezone(
'Asia/Kolkata'
)
obj1
=
tz.localize(obj1)
obj2
=
tz.localize(obj2)
print
(obj2
-
obj1)
print
(obj1
-
obj2)
print
(
type
(obj1
-
obj2))
Output :
-165 days, 0:49:47 164 days, 23:10:13 <class 'datetime.timedelta'>
Not just differences, timedelta objects can also be used for addition. If we add a timedelta object to a datetime object, we get another datetime object that has the timedelta factored in as the difference with the first datetime object. Let’s see the example :
Python
import
datetime
import
pytz
obj
=
datetime.datetime(
2001
,
11
,
15
,
1
,
20
,
25
)
diff
=
datetime.timedelta(days
=
90
, hours
=
1
)
new_obj
=
obj
+
diff
print
(new_obj)
Output:
2002-02-13 02:20:25
Преобразовать локальное время в UTC.
Если ваша программа предназначена для работы в разных часовых поясах, а параметр времени оказывает влияние на генерируемые события, то придерживайтесь простого, но очень важного правила:
- Всегда храните и работайте со временем в UTC. Если вам нужно сохранить оригинальные данные — пишите их отдельно. Никогда не храните локальное время и
tz
— Time Zone.
UTC — это зона без перехода на летнее время и без каких бы то ни было изменений в прошлом. Из UTC можно конвертировать время в локальное для любого часового пояса.
Дополнительно смотрите модуль zoneinfo
(добавлен в Python 3.9) — конкретная реализация часового пояса для поддержки базы данных часовых поясов IANA.
Синтаксис:
import datetime tz = datetime.timezone(offset, name=None)
Параметры:
offset
— объектdatetime.timedelta()
, смещение от UTC,name=None
— строка, название часового пояса.
Возвращаемое значение:
- объект смещения времени, который передается в качестве аргумента
tz
объектамdatetime.datetime()
иdatetime.time()
.
Описание:
Класс timezone()
модуля datetime
является подклассом datetime.tzinfo
, каждый экземпляр которого представляет часовой пояс, определенный фиксированным смещением от UTC.
Объекты этого класса не могут использоваться для представления информации о часовом поясе в местах, где разные смещение используются в разные дни года или когда были внесены исторические изменения в гражданское время.
Аргумент смещения offset
должен быть указан как объект datetime.timedelta(), представляющий разницу между местным временем и UTC. Смещение должно быть строго между -timedelta(hours=24)
и timedelta(hours=24)
, в противном случае появиться исключение ValueError
.
Аргумент name
не является обязательным. Если указано, то это должна быть строка, которая будет использоваться в качестве значения, возвращаемого методом datetime.tzname()
.
>>> import datetime >>> offset = datetime.timedelta(hours=3) >>> datetime.timezone(offset, name='МСК') # datetime.timezone(datetime.timedelta(0, 10800), 'МСК')
Методы экземпляра класса datetime.timezone()
:
tz.utcoffset(dt)
:
Метод tz.utcoffset()
возвращает фиксированное значение, указанное при создании экземпляра часового пояса.
Аргумент dt
игнорируется. Возвращаемое значение является экземпляром datetime.timedelta()
, равным разнице между местным временем и UTC.
Смещение UTC не ограничено целым числом минут.
>>> import datetime >>> offset = datetime.timedelta(hours=3) >>> tz = datetime.timezone(offset, name='МСК') >>> dt = datetime.datetime.now() >>> tz.utcoffset(dt) # datetime.timedelta(0, 10800) # или >>> dt = datetime.datetime.now(tz=tz) >>> dt.utcoffset() # datetime.timedelta(0, 10800)
tz.tzname(dt)
:
Метод tz.tzname()
возвращает фиксированное значение, указанное при создании экземпляра часового пояса.
Если имя часового пояса name
при создании экземпляра не указано, то имя, возвращаемое tzname(dt)
, генерируется из значения смещения следующим образом. Если смещение равно timedelta(0)
, то имя — UTC
, в противном случае это строка в формате UTC±HH:MM
, где ±
— это знак смещения, HH
и MM
— это две цифры offset.hours
и offset.minutes
соответственно.
>>> import datetime >>> offset = datetime.timedelta(hours=3) >>> tz = datetime.timezone(offset, name='МСК') >>> dt = datetime.datetime.now() >>> tz.tzname(dt) # 'МСК' # или >>> dt = datetime.datetime.now(tz=tz) >>> dt.tzname() # 'МСК'
tz.dst(dt)
:
Метод tz.dst()
всегда возвращает None
.
tz.fromutc(dt)
:
Метод tz.fromutc()
возвращает dt + offset
. Аргумент dt
должен быть «осведомленным» экземпляром datetime.datetime()
с tzinfo
, установленным в self
.
Атрибут класса datetime.timezone()
:
tz.utc
:
Атрибут tz.utc()
возвращает часовой пояс UTC, эквивалентно datetime.timezone(datetime.timedelta(0))
.
>>> import datetime >>> datetime.timezone(datetime.timedelta(0)) # datetime.timezone.utc
This tutorial demonstrates how to convert the time zone of a datetime object to another time zone such as CET,CST,EAT, EST, and UTC in the Python programming language.
This article contains the sections below:
Let’s dive into the Python code!
Import datetime Module & Create Example Data
As a first step, we have to import the datetime module to Python:
from datetime import datetime
To specify the different time zones in Python, we also have to load the pytz module:
Now, we can create a datetime object with the time zone UTC by applying the Python code below:
my_datetime = datetime(2023, 2, 13, 17, 10, 27, tzinfo = pytz.utc) print(my_datetime) # 2023-02-13 17:10:27+00:00
We can also format our datetime object to show the time zone using the strftime function:
my_datetime_utc = my_datetime.strftime('%Y-%m-%d %H:%M:%S %Z%z') print(my_datetime_utc) # 2023-02-13 17:10:27 UTC+0000
As you can see, our example date and time are the 13th of February 2023 at 05:10:27pm.
Let’s convert this date and time to different time zones.
Example 1: Convert datetime to CET Time Zone
If we want to convert a datetime object to the CET time zone, we can use the astimezone function and the time zone ‘Europe/Berlin’ as shown below:
my_datetime_cet = my_datetime.astimezone(pytz.timezone('Europe/Berlin')).strftime('%Y-%m-%d %H:%M:%S %Z%z') print(my_datetime_cet) # 2023-02-13 18:10:27 CET+0100
Example 2: Convert datetime to CST Time Zone
Similar to the Python code of Example 1, we can convert our example datetime object to CST by specifying ‘US/Central’ within the timezone function:
my_datetime_cst = my_datetime.astimezone(pytz.timezone('US/Central')).strftime('%Y-%m-%d %H:%M:%S %Z%z') print(my_datetime_cst) # 2023-02-13 11:10:27 CST-0600
Example 3: Convert datetime to EST Time Zone
In case we want to convert our time zone to EST, we have to specify ‘US/Eastern’:
my_datetime_est = my_datetime.astimezone(pytz.timezone('US/Eastern')).strftime('%Y-%m-%d %H:%M:%S %Z%z') print(my_datetime_est) # 2023-02-13 12:10:27 EST-0500
Video, Further Resources & Summary
Do you need more explanations on how to change the time zones of datetime objects in Python? Then you should have a look at the following video of the technologyCult YouTube channel.
In the video, the speaker explains how to convert time zones using the pytz package in Python.
Not enough? You could have a look at some other tutorials here on Statistics Globe:
- Convert Epoch Time to datetime Object & Vice Versa in Python
- Make Unaware datetime Time Zone Aware in Python
- Convert datetime to Unix Timestamp in Python
- Convert datetime Object to Local Time Zone
- Python Programming Tutorials
This post has shown how to transform datetime objects to other time zones in the Python programming language.
Note that we could use the code of this tutorial to convert datetime objects to many other time zones such as AEST, ACST, AFT, AKST, AST, CAT, EET, MSK, MST, PST, WAT, and WET as well. We simply would have to specify the corresponding region within the timezone function.
In case you have further questions, you may leave a comment below.
This tutorial was created in collaboration with Gottumukkala Sravan Kumar. Please have a look at Gottumukkala’s author page to get more information about his academic background and the other articles he has written for Statistics Globe.
In this tutorial, we will learn how to work with timezone in Python.
After reading this article, you’ll learn:
- Handling of timezone by creating a timezone aware date and time.
- How to get the current time in a different timezone
- Get the current timezone name, UTC offset, and DST offset if DST is in effect
- How to convert UTC Datetime to a specific timezone
- Convert time from one timezone to another
- Mathematical operations on two timezone-aware and timezone naive objects
- Learn the tzinfo implementation modules namely pytz, ZoneInfo, and their methods.
Table of contents
- What is timezone in Python?
- Create Timezone Aware Datetime Object
- Create TimeZone Aware Datetime Object Using timezone class
- Get Current Time in Different Timezone
- Get TimeZone Information Using tzinfo
- Converting Between Timezones
- Working with Local Timezones
What is timezone in Python?
A time zone represents the standardized time depending on which part of the world is being considered.
In simple terms, timezone refers to the local time of a region. UTC (Coordinated Universal Time) is the astronomical time based on earth’s rotation, is the standard against which the world’s region-based time is coordinated.
Note: UTC – Coordinated Universal Time is the common time standard across the world. So, in Python, to work with the timezone without any issues, it is recommended to use the UTC as your base timezone
For example, CT(Central Time) in North and South America is either 5 or 6 hours behind and represented as UTC-5 or UTC-6 based on the Day Light Saving. Below are a few examples.
UTC Offset | Locations | Name | Location |
---|---|---|---|
UTC +9 | Japan, South Korea, and 5 more | JST | Tokyo |
UTC +5:30 | India | IST | India |
UTC +1 | The United Kingdom and 20 more | BST | London |
UTC -10 | Hawaii/USA and 2 more | HST | Honolulu |
Python provides the datetime.tzinfo
abstract base class which provides methods to handle timezone. But this class is an abstract base class and should not be instantiated directly. We need to define a subclass of tzinfo to capture information about a particular time zone.
The pytz library has implemented a timezone class for handling arbitrary fixed offsets from UTC and timezones. This library allows accurate and cross-platform timezone calculations and also solves the issue of ambiguous times at the end of daylight saving time.
pytz is a concrete implementation of the abstract base class tzinfo and is used to create timezone-aware datetime objects.
For example, The datetime.now()
function returns the current local date-time without any timezone information. Using the pytz library, we can pass the timezone name to this function to get the current datetime in the given timezone.
We’ll use the following attributes and methods of the pytz module to work with timezone in Python.
pytz.utc
: Get the standard UTC timezonepytz.timezone('region')
: Create the timezone object of a particular regionpytz.astimezone()
: Convert the time of a particular time zone into another time zone
Create Timezone Aware Datetime Object
In Python, a date object can be mentioned with or without timezones. Based on that, an object is known as Naive or Aware. A date object, by default, is naive. A datetime or time object is aware if it holds the timezone(tz) value.
Follow the below steps to create a timezone aware Datetime Object in Python: –
- Install pytz module if not installed using the
pip install pytz
command. - Use the
pytz.timezone('region_name')
function to create the timezone object - Use the
datetime.now(timezone_obj)
ordatetime.datetime('timezone')
function to create the timezone aware current datetime.
Example:
from datetime import datetime
import pytz
# current Datetime
unaware = datetime.now()
print('Timezone naive:', unaware)
# Standard UTC timezone aware Datetime
aware = datetime.now(pytz.utc)
print('Timezone Aware:', aware)
# US/Central timezone datetime
aware_us_central = datetime.now(pytz.timezone('US/Central'))
print('US Central DateTime', aware_us_central)
Output:
Timezone naive: 2021-07-09 13:22:02.256978
Timezone Aware: 2021-07-09 07:52:02.256978+00:00
US Central DateTime 2021-07-09 02:52:02.313026-05:00
- To get the UTC time we used the
pytz.utc
as a parameter todatetime.now()
function. The offset at the end is +00:00 which is the standrad UTC offset. - To get the CDT datetime, we used the ‘US/Central’ region to create a timezone. The offset at the end is -05:00 is the UTC offset of the CDT region
Refer to list all timezones in Python if you don’t know the exact name of the timezone to create a date and time in the right timezone.
To make the old/existing datetime timezone aware, use the following code.
from datetime import datetime
import pytz
unaware = datetime(2021, 6, 15, 8, 45, 17, 5)
print('Timezone naive:', unaware)
# Convert unaware Datetime to UTC timezone aware Datetime
aware = unaware.replace(tzinfo=pytz.UTC)
print(aware)
Note: The datetime.replace()
method return the new datetime
instance.
Format UTC DateTime to Get the timezone name
Extract the timezone name from UTC DateTime using the DateTime formatting in Python. Use the %Z
directive to get the timezone name.
from datetime import datetime
import pytz
datetime_india = datetime.now(pytz.timezone('Asia/Kolkata'))
print("Formatted DateTime in IST : ", datetime_india.strftime('%Y:%m:%d %H:%M:%S %Z %z'))
# Output 2021:07:08 17:53:23 IST +0530
Note: IST is the timezone name
Create TimeZone Aware Datetime Object Using timezone class
Let’s see how create a timezone aware datetime
object without pytz.
The datetime modules have the timezone
class, which in turn is the subclass of the abstract base class tzinfo
. Each instance created of the timezone class represents the offset of the timezone from the Coordinated Universal Time (UTC).
We can create an UTC-aware datetime
object by assigning the timezone.utc
Syntax:
datetime.timezone(offset, name=None)
Here offset
represents the difference between the local time and the UTC (Coordinated Universal Time). It can be a time delta object ranging from hours=-24 to +24.
Example:
from datetime import datetime, timezone, timedelta
# naive
naive = datetime.now()
print("Naive DateTime:", naive)
# UTC aware
UTC = datetime.now(timezone.utc)
print("UTC DateTime", UTC)
# Creating a datetime with JST (Japan) TimeZone
jst_dateTime = datetime.now(timezone(timedelta(hours=+9), 'JST'))
print("In JST::", jst_dateTime)
Note: we are setting the UTC offset using the timedelta class timedelta(hours=+9)
Get Current Time in Different Timezone
Using the pytz module we can get the current date and time of any timezone.
Syntax:
datetime.now(pytz.timezone('timezone name'))
Steps:
- Use the
pytz.timezone('region_name')
function to create the timezone object - Use
datetime.now(timezone_obj)
function to get the current datetime of the given timezone.
Note: UTC – Coordinated Universal Time is the common time standard across the world. So, to work with the timezone without any issues, it is recommended to use the UTC as your base timezone.
In this example, we’ll see how to get the current datetime in the following timezones
USA: Get current Date and Time in the following TimeZones of United States
from datetime import datetime
import pytz
dt_us_central = datetime.now(pytz.timezone('America/Mexico_City'))
print("US Central DateTime:", dt_us_central.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_us_pacific = datetime.now(pytz.timezone('America/Tijuana'))
print("US Pacific timezone DateTime:", dt_us_pacific.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_us_eastern = datetime.now(pytz.timezone('America/New_York'))
print("US Eastern timezone DateTime:", dt_us_eastern.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_us_mountain = datetime.now(pytz.timezone('America/Chihuahua'))
print("US Mountain timezone DateTime:", dt_us_mountain.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
Output:
US Central DateTime: 2021:07:08 08:37:34 CDT -0500 US Pacific timezone DateTime: 2021:07:08 06:37:34 PDT -0700 US Eastern timezone DateTime: 2021:07:08 09:37:34 EDT -0400 US Mountain timezone DateTime: 2021:07:08 07:37:34 MDT -0600
Other TimeZones
from datetime import datetime
import pytz
dt_japan = datetime.now(pytz.timezone('Asia/Tokyo'))
print("Japan DateTime:", dt_japan.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_brazil = datetime.now(pytz.timezone('America/Sao_Paulo'))
print("Brazil DateTime:", dt_brazil.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_uk = datetime.now(pytz.timezone('Europe/London'))
print("Uk DateTime:", dt_uk.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_germany = datetime.now(pytz.timezone('Europe/Berlin'))
print("Germany DateTime:", dt_germany.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_aus = datetime.now(pytz.timezone('Australia/Canberra'))
print("Australia Oceanic DateTime:", dt_aus.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
dt_africa = datetime.now(pytz.timezone('Africa/Maputo'))
print("Central Africa: DateTime:", dt_africa.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
Output:
Japan DateTime: 2021:07:09 12:02:38 JST +0900 Brazil DateTime: 2021:07:09 00:02:38 -03 -0300 Uk DateTime: 2021:07:09 04:02:38 BST +0100 Germany DateTime: 2021:07:09 05:02:38 CEST +0200 Australia Oceanic DateTime: 2021:07:09 13:02:38 AEST +1000 Central Africa: DateTime: 2021:07:09 05:02:38 CAT +0200
Also, see: Convert between timezones
Get TimeZone Information Using tzinfo
The datetime.tzinfo
is an abstract base class containing information about the date or time object passed to them.
The tzinfo generally contains the following information: –
- The time zone name of a Datetime
- Offset from the UTC (Coordinated Universal Time)
- The DST(Daylight saving).
The tzinfo class provides the following method to get the timezone information: –
tzinfo.tzname(dt)
: Returns the time zone name corresponding to thedatetime
objectdt
. This method returns the name that is used while creating the timezone objecttzinfo.utcoffset(dt)
: This method returns the total offset from the UTC which should be a timedelta object. The values of the timedelta is positive if it is east of UTC and negative for the west of UTC. The total offset includes both timezone and the DST(Day light savings) values. The range of the timedelta is therfore between -timedelta(hours=24) to timedelta(hours=24)tzinfo.dst(dt)
: This method returns dst offset in the zones where dst is in effect. In other cases it will return onlytimedelta(0)
. The dst information is already part of the the utcoffset therefore the tz.utcoffset(dt) - tz.dst(dt)
should return the standard offset of the timezone irrespective of the date and time but only on the geographic location.
Example:
from datetime import datetime
import pytz
# timezone: US Central Time
dt_us_central = datetime.now(pytz.timezone('America/Mexico_City'))
print("US Central DateTime:", dt_us_central.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
# Get current TimeZone name
print(dt_us_central.tzname())
# Get UTC Offset
print(dt_us_central.utcoffset())
# Get the daylight saving time (DST offset) adjustment
print(dt_us_central.dst())
Our code produced the following information:
US Central DateTime: 2021:07:08 22:30:06 CDT -0500 TimeZone Name: CDT UTC Offset -1 day, 19:00:00 DST: 1:00:00
The datetime modules have the timezone
class, which in turn is the subclass of the abstract base class tzinfo
Converting Between Timezones
Use the datetime.astimezone()
method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.
import datetime
import pytz
# UTC timezone Datetime
dt_local = datetime.datetime.now(pytz.utc)
print("UTC DateTime:", dt_local.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
# convert UTC timezone to 'US/Central'
dt_us_central = dt_local.astimezone(pytz.timezone('US/Central'))
print("US Central DateTime:", dt_us_central.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
# Convert 'US/Central' timezone to US/Eastern
dt_us_eastern = dt_us_central.astimezone(pytz.timezone('America/New_York'))
print("US Eastern DateTime:", dt_us_eastern.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
# Convert US/Eastern timezone to IST (India) timezone
dt_ind = dt_us_eastern.astimezone(pytz.timezone('Asia/Kolkata'))
print("India DateTime:", dt_ind.strftime("%Y:%m:%d %H:%M:%S %Z %z"))
Output:
UTC DateTime: 2021:07:09 07:19:02 UTC +0000 US Central DateTime: 2021:07:09 02:19:02 CDT -0500 US Eastern DateTime: 2021:07:09 03:19:02 EDT -0400 India DateTime: 2021:07:09 12:49:02 IST +0530
Note: To work with the timezone without any issues, it is recommended to use the UTC as your base timezone not a local time.
As already mentioned, we can convert a naive datetime to an aware datetime instance with a timezone value set to a local standardized value.
We can do it with one of the pytz
methods called localize
() .This method is used to convert a naive to local time. It accepts the two arguments, namely the datetime object to localize and an optional is_dst
flag.
This flag is set to true if we want to localize and the daylight saving information and false if we want only the standard offset time and false otherwise.
As mentioned above the tzinfo
has a method called dst()
which will return the Daylight Saving Time(DST) information if the flag is set to true.
Let us see an example to show how we can set a local time zone and get the DST information.
from datetime import datetime
import pytz
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# Indian Standard Time
tz_india = pytz.timezone('Asia/Kolkata')
ist_local = tz_india.localize(datetime.now())
print("Indian Standard Time::", ist_local.strftime(fmt))
# Europe/Amsterdam Time
amdam_tz = pytz.timezone('Europe/Amsterdam')
dt = datetime(1983, 8, 3, 2, 0, 0)
cest_local = amdam_tz.localize(dt, is_dst=True)
print("Amsterdam with daylight saving time::", cest_local.strftime(fmt))
# Day Light Saving
print("Daylight saving time in amsterdam on 3/8/83::", cest_local.tzinfo.dst(cest_local))
Output
Indian Standard Time:: 2021-03-09 14:04:37 IST+0530 Amsterdam with daylight saving time:: 1983-08-03 02:00:00 CEST+0200 Daylight saving time in amsterdam on 3/8/83:: 1:00:00
Improve Article
Save Article
Improve Article
Save Article
In this article, we will discuss how to convert date and time with different timezones in Python. To do this we will use one of the modules of python pytz . This module brings the Olson tz database into Python and this library allows accurate and cross-platform timezone calculations using Python. The method pytz.timezone() generates the current timezone of a particular region.
Syntax:
pytz.timezone(“name of the time zone”)
Ex: pytz.timezone(“Asia/Kolkata”)
Example 1:
In the below program the current UTC time is converted according to Asia/Kolkata timezone.
Python3
from
datetime
import
datetime
import
pytz
UTC
=
pytz.utc
IST
=
pytz.timezone(
'Asia/Kolkata'
)
print
(
"UTC in Default Format : "
,
datetime.now(UTC))
print
(
"IST in Default Format : "
,
datetime.now(IST))
datetime_utc
=
datetime.now(UTC)
print
(
"Date & Time in UTC : "
,
datetime_utc.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
datetime_ist
=
datetime.now(IST)
print
(
"Date & Time in IST : "
,
datetime_ist.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
Output:
Example 2:
Here is another program where the current Asia/Kolkata timezone is converted to US/Eastern timezone.
Python3
from
datetime
import
datetime
import
pytz
original
=
pytz.timezone(
'Asia/Kolkata'
)
converted
=
pytz.timezone(
'US/Eastern'
)
dateTimeObj
=
datetime.now(original)
print
(
"Original Date & Time: "
,
dateTimeObj.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
dateTimeObj
=
datetime.now(converted )
print
(
"Converted Date & Time: "
,
dateTimeObj.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
Output:
One can get all timezone values present in the pytz by executing the below code:
for timezone in pytz.all_timezones: print(timezone)
Below is a program to convert a particular timezone to multiple timezones of the Indian region:
Python3
from
datetime
import
datetime
import
pytz
original
=
pytz.utc
dateTimeObj
=
datetime.now(original)
print
(
"Original Date & Time: "
,
dateTimeObj.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
for
timeZone
in
pytz.all_timezones:
if
'Indian/'
in
timeZone:
dateTimeObj
=
datetime.now(pytz.timezone(timeZone))
print
(timeZone,
":"
,dateTimeObj.strftime(
'%Y:%m:%d %H:%M:%S %Z %z'
))
Output:
In this article, we will discuss how to convert local datetime to UTC timezone in python.
Suppose you are in a timezone that is not UTC. But you have a datetime in your local timezone, and you want to convert it to UTC timezone. For example, if you are in Asia/Calcutta timezone and timestamp in your local time zone is,
10/21/2021 08:18:19
Now you want to convert it to UTC timezone, and the result should be like,
10/21/2021 02:48:19
Before we start looking into the solutions, an important point to understand is that these solutions will apply to all time zones. It means, whatever your local timezone is, you can easily convert the datetime to UTC format using these solutions. Let’s start looking into them one by one.
We will use the datetime module for this. First, we will create a datetime object from a string. This datetime object will have no timezone associated with it, and it means it can be considered as of local timezone. Then we will change the timezone of the datetime object to UTC by calling the astimezone() function on the datetime object.
Advertisements
The astimezone() function accepts a timezone instance tz as an argument. It returns a new DateTime instance according to the specified time zone parameter tz, i.e., it converts the time in calling datetime to the specified timezone and returns a new datetime object containing it.
Let’s use this to convert local time to UTC i.e.
from datetime import datetime import pytz dt_str = "10/21/2021 8:18:19" format = "%m/%d/%Y %H:%M:%S" # Create datetime object in local timezone local_dt = datetime.strptime(dt_str, format) print('Datetime in Local Time zone: ', local_dt) # Convert local datetime to UTC time-zone datetime dt_utc = local_dt.astimezone(pytz.UTC) print('Datetime in UTC Time zone: ', dt_utc) dt_utc_str = dt_utc.strftime(format) print('Datetime string in UTC Time zone: ', dt_utc_str)
Output:
Datetime in Local Time zone: 2021-10-21 08:18:19 Datetime in UTC Time zone: 2021-10-21 02:48:19+00:00 Datetime string in UTC Time zone: 10/21/2021 02:48:19
Convert timezone of datetime object from local to UTC in Python
Instead of string, if you already have the datetime object with local timezone (or null timezone), we can convert it directly to the datetime object with UTC timezone using astimezone(). For example,
from datetime import datetime import pytz # Create datetime object in local timezone local_dt = datetime(2021, 10, 4, 9, 10, 34, 300030) print('Datetime in Local Time zone: ', local_dt) # Convert local datetime to UTC time-zone datetime dt_utc = local_dt.astimezone(pytz.UTC) print('Datetime in UTC Time zone: ', dt_utc)
Output:
Datetime in Local Time zone: 2021-10-04 09:10:34.300030 Datetime in UTC Time zone: 2021-10-04 03:40:34.300030+00:00
Convert the current local time to UTC in Python
Suppose we have a datetime object that contains the current time in the local timezone, and it has the timezone information associated with it. Using astimezone(), we can convert it to UTC timezone and get the current UTC. For that, we will pass the pytz.UTC as argument to astimezone() function. For example,
from datetime import datetime import pytz # Get current time in local timezone local_dt = datetime.now() print('Current Local Time: ', local_dt) # Convert local to UTC timezone dt_utc = local_dt.astimezone(pytz.UTC) print('Current time in UTC Time-zone: ', dt_utc)
Output:
Current Local Time: 2021-10-17 10:12:55.502825 Current time in UTC Time-zone: 2021-10-17 04:42:55.502825+00:00
Summary:
We learned how to convert local time to UTC timezone in python.
Advertisements
Thanks for reading.