Converting Local Time Strings to UTC
In Python, converting a datetime string in local time to a string in UTC time involves the following steps:
Example Code:
from datetime import datetime import pytz # Given local time string local_time_str = "2008-09-17 14:02:00" # Local timezone local_timezone = pytz.timezone("America/New_York") # Parse local time string into naive datetime naive_datetime = datetime.strptime(local_time_str, "%Y-%m-%d %H:%M:%S") # Localize naive datetime with timezone local_datetime = local_timezone.localize(naive_datetime) # Convert to UTC utc_datetime = local_datetime.astimezone(pytz.utc) # Resultant UTC time string utc_time_str = utc_datetime.strftime("%Y-%m-%d %H:%M:%S") print(utc_time_str) # Output: 2008-09-17 04:02:00
This code snippet demonstrates the conversion from local time (America/New_York, UTC -5) to UTC, resulting in a string representation of the UTC time.
The above is the detailed content of How Can I Convert a Local Time String to a UTC Time String in Python?. For more information, please follow other related articles on the PHP Chinese website!