Cara menggunakan python convert timezone

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 OffsetLocationsNameLocationUTC +9Japan, South Korea, and 5 moreJSTTokyoUTC +5:30IndiaISTIndiaUTC +1The United Kingdom and 20 moreBSTLondonUTC -10Hawaii/USA and 2 moreHSTHonoluluTimeZones

Python provides the 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:007 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 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:008 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.

  • 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:009: Get the standard UTC timezone
  • 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)0: Create the timezone object of a particular region
  • 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)1: 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 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)2 command.
  • Use the 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)3 function to create the timezone object
  • Use the 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)4 or 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)5 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 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:009 as a parameter to 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:008 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 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)8 method return the new 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)9 instance.

Format UTC DateTime to Get the timezone name

Extract the timezone name from UTC DateTime using the DateTime formatting in Python. Use the 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 +05300 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 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)9 object without pytz.

The datetime modules have the 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 +05302 class, which in turn is the subclass of the abstract base class 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 +05303. 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 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)9 object by assigning the 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 +05305

Syntax:

datetime.timezone(offset, name=None)

Here 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 +05306 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 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 +05307

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 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)3 function to create the timezone object
  • Use 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)4 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:

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:000

Also, see: Convert between timezones

Get TimeZone Information Using tzinfo

The 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:007 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: –

  • datetime.timezone(offset, name=None)1: Returns the time zone name corresponding to the 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)9 object datetime.timezone(offset, name=None)3. This method returns the name that is used while creating the timezone object
  • datetime.timezone(offset, name=None)4: 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)
  • datetime.timezone(offset, name=None)5: This method returns dst offset in the zones where dst is in effect. In other cases it will return only datetime.timezone(offset, name=None)6. The dst information is already part of the the utcoffset therefore the tdatetime.timezone(offset, name=None)7 should return the standard offset of the timezone irrespective of the date and time but only on the geographic location.

Example:

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:001

Our code produced the following information:

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:002

The datetime modules have the 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 +05302 class, which in turn is the subclass of the abstract base class 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 +05303

Converting Between Timezones

Use the 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) 0 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.

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:003

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:004

Working with Local Timezones

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 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) 1 methods called 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) 2() .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 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) 3 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 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 +05303 has a method called 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) 5 which will return the Daylight Saving Time(DST) information if the flag is set to true.

Postingan terbaru

LIHAT SEMUA