SoFunction
Updated on 2025-04-28

Python handles date and time data with time zones

Basic time zone information

In the time zone information:

  • “PRC”
  • “Asia/Shanghai”
  • “ETC/GMT-8”

They all said: East Eight District +8, equivalent to China's standard time zone

Here we use an auxiliary library pytz to operate the time zone. All time zones supported by this library are as follows:

import pytz
print(pytz.all_timezones)

You can also choose the time zone according to the country:

from pytz import country_names, country_timezones
all_timezones = [country_timezones.get(country) for country in country_names]

python datetime uses timezone

Get the current UTC time:

import pytz
from datetime import datetime
from pytz import timezone

now_utc_dt = (tz=)  # Current UTC timenow_china_dt = now_utc_dt.astimezone(timezone('PRC'))  #datetime to utc+8 time: the current actual timeprint(now_china_dt)

Directly transfer to UTC time at any time

create_china_dt = datetime(2024, 1, 1, tzinfo=timezone("ETC/GMT-8"))
print(create_china_dt)

You can get the following information: (2024, 1, 1, 0, 0, tzinfo=<StaticTzInfo 'Etc/GMT-8'>)

Pandas handles time zone data

1. Convert any data into data containing time zone information

import pandas as pd

dt_list = ["2024-01-01 12:00:00", "2024-01-02 12:00:00", "2024-01-03 12:00:00"]
dt_series = pd.to_datetime(dt_list, utc=True)  # Load data in UTC standard time

2. Time zone conversion

berlin_dt = dt_series.tz_convert('Europe/Berlin')
sh_dt = dt_series.tz_convert('Asia/Shanghai')
print(f"Europe/BerlinTime display: {berlin_dt.strftime('%Y-%m-%d %H:%M:%S')}")  # Convert to Europe/Berlin time zone (+1)print(f"Asia/ShanghaiTime display: {sh_dt.strftime('%Y-%m-%d %H:%M:%S')}")  # Convert to Europe/Berlin time zone (+1)print(f"UTCTime display: {dt_series.tz_convert('UTC').strftime('%Y-%m-%d %H:%M:%S')}")  # Convert to UTC time

Get the result:

Europe/Berlin time display: Index(['2024-01-01 13:00:00', '2024-01-02 13:00:00', '2024-01-03 13:00:00'], dtype='object')
Asia/Shanghai time display: Index(['2024-01-01 20:00:00', '2024-01-02 20:00:00', '2024-01-03 20:00:00'], dtype='object')
UTC time display: Index(['2024-01-01 12:00:00', '2024-01-02 12:00:00', '2024-01-03 12:00:00'], dtype='object')

3. Time difference between different time zones

print(f'The time interval between the two time zones(Second): {(berlin_dt - sh_dt).seconds}')

Get the result:

The time interval between the difference between two time zones (seconds): Int64Index([0, 0, 0], dtype='int64')

In actual operations, they can be converted to UTC time and then calculated

4. Remove time zone information

remove_dt = dt_series.tz_convert('Asia/Shanghai')
print(f"Exclude time zone: {remove_dt.tz_localize(None)}")  # Directly remove time zone information at the time point corresponding to the currently reserved time zone, which is often used for operations before terminal displaying data.

Get the result:

Exclude time zone: DatetimeIndex(['2024-01-01 20:00:00', '2024-01-02 20:00:00', '2024-01-03 20:00:00'], dtype='datetime64[ns]', freq=None)

Knowledge extension

When dealing with time and dates in Python, it goes without saying that the importance of understanding local time and time zones is self-evident. Local time, also known as local standard time, refers to the time used in a specific geographical location. The time zone is the division of the time used in different regions on the earth, and is used to adjust the time difference between different regions.

Python provides multiple libraries to handle time and time zones, the most commonly used are datetime and pytz libraries. The datetime library provides basic functionality for handling dates and times, while the pytz library provides support for time zones.

Get and display local time

First, we usedatetimelibrary to get and display local time. Here is a simple example:

import datetime

# Get the current local timenow = ()

# Show the current local timeprint("Current local time:", now)

Convert local time to other time zone time

To handle the time zone, we need to usepytzlibrary.pytzThe library supports almost all time zones and provides the ability to convert local time to other time zones. The following is a usepytzExample of library to handle time zones:

import datetime
import pytz

# Get the current local timenow = ()

# Get the local time zonelocal_tz = ('Asia/Shanghai')

# Convert local time to local time zone timelocal_time = local_tz.localize(now)

# Show local time zoneprint("Current local time zone time:", local_time)

# Convert to other time zoneother_tz = ('America/New_York')
other_time = local_time.astimezone(other_tz)

# Show other time zonesprint("Other time zones after conversion:", other_time)

Python time zone processing

In Python, it is very important to handle time zones correctly, especially when doing date and time calculations across time zones. The datetime module in the Python standard library provides basic date and time processing capabilities, but to handle time zones, we usually need to rely on third-party libraries such as pytz and dateutil.

The pytz library is the most commonly used time zone processing library in Python. It provides a large number of time zone definitions, allowing you to easily create datetime objects with specific time zones. The pytz library also supports complex rules related to daylight saving time and other time zones.

Here is a simple example of using pytz to handle time zones:

import pytz
from datetime import datetime

# Create a datetime object with UTC time zoneutc_dt = ()
print("UTC Time:", utc_dt)

# Create a datetime object with a specific time zone, such as Eastern Time in New York, USA (EST/EDT)ny_tz = ('America/New_York')
ny_dt = (ny_tz)
print("New York Time:", ny_dt)

# Convert time zoneutc_from_ny = ny_dt.astimezone()
print("Time to switch from New York to UTC:", utc_from_ny)

Apart from pytz, the dateutil library is also a very useful tool, especially when dealing with complex date and time issues. The dateutil library can parse date and time strings in various formats and provides some practical date and time operation functions.

When dealing with time zones, you also need to pay attention to the zoneinfo module in the standard library after Python 3.9. The zoneinfo module provides an API similar to pytz for processing time zone information, but it is lighter and is part of the Python standard library.

Some best practices when dealing with time zones include:

Always clarify the time zone your data uses and convert it to UTC for storage and transfer where possible.

When performing cross-time zone calculations, use special time zone processing libraries such as pytz or zoneinfo.

Avoid hard-code time zone offsets in your code, as time zone rules may change. Use a time zone database (as provided by pytz) to make sure your code can handle these changes.

Python provides a variety of tools and libraries to deal with time zone-related issues. Using these tools correctly ensures that your code has the correct time zone awareness when dealing with dates and times, thus avoiding common time zone-related errors.

Python get time zone information

When we need to get the current time zone information in Python, we can use the pytz module in the Python standard library. The pytz module provides time zone information that is tightly integrated with Python's datetime module. It allows us to fetch, convert and compare times in different time zones.

First, make sure that the pytz module is already installed. If it has not been installed, you can install it through pip:

pip install pytz

After the installation is complete, we can use the pytz module in Python scripts to obtain time zone information. Here is a simple example showing how to get the name of the current time zone and the current time:

import datetime
import pytz

# Get the current time zonecurrent_tz = ('Asia/Shanghai')

# Get the current timenow = (current_tz)

print("Current time zone:", current_tz)
print("Current time:", now)

In the example above, we used 'Asia/Shanghai' as the name of the time zone, which represents the time zone where Shanghai is located. The pytz module supports time zones around the world, and you can choose the appropriate time zone name as needed.

In addition to getting the current time zone information, the pytz module also provides many other functions. For example, you can convert times between different time zones, compare whether the times in different time zones are equal, and perform other time zone-related operations.

The time zone information provided by the pytz module is based on the IANA time zone database. This means it will be updated over time to reflect changes in global time zone rules. Therefore, when using the pytz module, it is recommended to periodically check and update your time zone information to ensure accuracy.

The pytz module in Python provides a convenient way to obtain and process time zone information. By using it, you can easily deal with time zone-related issues in your Python program.

This is the end of this article about python processing date and time data with time zones. For more information about python processing time zones, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!