Home >Backend Development >Python Tutorial >How to Convert Local Time Strings to UTC?
Converting Local Time Strings to UTC
In many applications, it is necessary to convert timestamps from local time zones to Coordinated Universal Time (UTC) to ensure consistent handling across different geographical regions. This is particularly important for tasks such as scheduling, data exchange, and synchronization.
To convert a datetime string from local time to UTC, follow these steps:
Here is an example code snippet using the local timezone "America/Los_Angeles" and the string "2001-2-3 10:11:12":
from datetime import datetime import pytz local = pytz.timezone("America/Los_Angeles") naive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S") local_dt = local.localize(naive, is_dst=None) utc_dt = local_dt.astimezone(pytz.utc) utc_str = utc_dt.strftime("%Y-%m-%d %H:%M:%S") print(utc_str) # Output: 2001-02-03 04:11:12
By following these steps, you can reliably convert local time strings to UTC, ensuring consistent handling of timestamps across different time zones.
The above is the detailed content of How to Convert Local Time Strings to UTC?. For more information, please follow other related articles on the PHP Chinese website!