Home > Backend Development > Python Tutorial > How to Convert UTC Datetime Strings to Local Timezones in Python?

How to Convert UTC Datetime Strings to Local Timezones in Python?

Barbara Streisand
Release: 2024-11-30 10:32:13
Original
479 people have browsed it

How to Convert UTC Datetime Strings to Local Timezones in Python?

Converting UTC Datetime Strings to Local Datetimes

Question:

How to convert a UTC datetime string, stored as a string in App Engine's Bigtable, into a datetime in the end-user's correct timezone?

Answer:

To convert a UTC datetime string into a datetime in the user's correct timezone, one can use the python-dateutil library. This library provides tzinfo implementations on top of a zoneinfo (Olson) database, allowing for easy referencing of time zone rules by canonical names.

Implementation:

from datetime import datetime
from dateutil import tz

# Hardcode zones:
from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/New_York')

# Auto-detect zones:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

# Create a datetime object from the UTC string
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')

# Convert the datetime object to UTC timezone
utc = utc.replace(tzinfo=from_zone)

# Convert the datetime object to the user's timezone
local = utc.astimezone(to_zone)
Copy after login

Recommended Storage for Timezone Information:

  • "-5:00" or "EST": This method is simple but limited as it assumes a constant offset for the user's timezone.
  • Canonical names: Using canonical names from the Olson database is more flexible and timezone-aware, as it takes into account historical changes in time zones. The python-dateutil library allows for referencing timezones by canonical names.

For example, "-5:00" can be converted to "America/New_York" using:

import pytz
est = pytz.timezone("America/New_York")
est_name = est.zone
Copy after login

The above is the detailed content of How to Convert UTC Datetime Strings to Local Timezones in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template