Home > Backend Development > Python Tutorial > How to Convert a UTC Datetime String to Local Time in Python?

How to Convert a UTC Datetime String to Local Time in Python?

Barbara Streisand
Release: 2024-12-07 04:20:14
Original
226 people have browsed it

How to Convert a UTC Datetime String to Local Time in Python?

Converting UTC Datetime String to Local Datetime

Converting UTC Time to Local Time Zone

In your scenario, you have a UTC datetime string stored in BigTable that you need to convert to a Python datetime object in the user's local time zone.

Using the python-dateutil library, you can easily accomplish this conversion:

from dateutil import tz

utc_string = "2011-01-21 02:37:21"
utc_datetime = datetime.strptime(utc_string, '%Y-%m-%d %H:%M:%S')

# Assuming EST -5 time zone
local_zone = tz.gettz('America/New_York')

# Convert UTC datetime to local time
local_datetime = utc_datetime.astimezone(local_zone)
Copy after login

Storing Time Zone Information

As for storing time zone information, a common approach is to use the Olson database (tzinfo). This database provides a canonical representation of time zone rules.

You can then specify a time zone by its unique identifier, such as "America/New_York" or "-5". Python's tzinfo library offers methods to get information about different time zones and create instances of timezone objects for use in datetime comparisons.

Additional Notes

  • The python-dateutil library also includes a helper method called fromtimestamp that can take a timestamp and return a timezone-aware datetime object.
  • You can use the tzlocal package to automatically detect the system's current time zone.

The above is the detailed content of How to Convert a UTC Datetime String to Local Time 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