Conversion of Local Time String to UTC
Converting a datetime string in local time to its corresponding UTC equivalent can be achieved through a series of steps.
Step 1: Parsing the String
Initialize the string as a "naive" datetime object, which lacks any explicit timezone information.
Step 2: Determining Local Timezone
Using the pytz library, identify the local timezone and create a corresponding timezone object.
Step 3: Local Timezone Manipulation
Attach the local timezone information to the naive datetime object.
Step 4: UTC Conversion
Utilize the astimezone() method of the local timezone object to convert the datetime to UTC.
Step 5: Formatting
Format the UTC datetime string using the strftime() method as required.
Example Code
Consider a local timezone of "America/Los_Angeles" and a datetime string "2001-2-3 10:11:12".
from datetime import datetime import pytz # Parse the datetime string into a naive object naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S") # Determine the local timezone local = pytz.timezone("America/Los_Angeles") # Attach the local timezone to the naive datetime local_dt = local.localize(naive, is_dst=None) # Convert to UTC utc_dt = local_dt.astimezone(pytz.utc) # Format the UTC datetime string utc_date_string = utc_dt.strftime("%Y-%m-%d %H:%M:%S")
The above is the detailed content of How to Convert a Local Time String to UTC in Python?. For more information, please follow other related articles on the PHP Chinese website!