📅  最后修改于: 2023-12-03 15:19:37.318000             🧑  作者: Mango
Pytz is a Python library that provides timezone database and is widely used for working with different timezones in Python applications. It is based on the Olson timezone database and is compatible with Python 2 and 3.
To install Pytz, you can use pip:
pip install pytz
To use Pytz, you first need to import the library:
import pytz
To localize a naive datetime object to a specific timezone, you can use the timezone
function:
import datetime
from pytz import timezone
d = datetime.datetime(2021, 10, 1, 12, 0, 0)
tz = timezone('US/Pacific')
localized_date = tz.localize(d)
print(localized_date)
# Output: 2021-10-01 12:00:00-07:00
To convert a timezone-aware datetime object to another timezone, you can use the astimezone
method:
import datetime
from pytz import timezone
d = datetime.datetime(2021, 10, 1, 12, 0, 0, tzinfo=pytz.utc)
new_tz = timezone('US/Pacific')
converted_date = d.astimezone(new_tz)
print(converted_date)
# Output: 2021-10-01 05:00:00-07:00
Pytz provides timezone database with over 500 regions. To access the database, you can use the all_timezones
or common_timezones
function:
import pytz
all_timezones = pytz.all_timezones
common_timezones = pytz.common_timezones
print(all_timezones[:10])
# Output: ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Asmera', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau']
print(common_timezones[:10])
# Output: ['Africa/Abidjan', 'Africa/Accra', 'Africa/Addis_Ababa', 'Africa/Algiers', 'Africa/Asmara', 'Africa/Bamako', 'Africa/Bangui', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Blantyre']
In summary, Pytz is a powerful Python library for timezone localization and manipulation. With its timezone database and easy-to-use API, it makes working with timezones in Python applications a breeze.