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)
Recommended Storage for Timezone Information:
For example, "-5:00" can be converted to "America/New_York" using:
import pytz est = pytz.timezone("America/New_York") est_name = est.zone
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!