Home > Backend Development > Python Tutorial > How Can I Convert Local Time Strings to UTC in Python?

How Can I Convert Local Time Strings to UTC in Python?

Susan Sarandon
Release: 2024-11-30 22:45:12
Original
322 people have browsed it

How Can I Convert Local Time Strings to UTC in Python?

Converting Local Time Strings to UTC

In certain scenarios, we may encounter the need to convert a datetime string from local time to UTC. To achieve this, we can utilize Python's datetime and pytz modules.

Step 1: Parsing the Local Time String

Begin by parsing the local time string into a naive datetime object. A naive datetime lacks timezone information.

Step 2: Identifying the Local Timezone

Next, determine the local timezone using the pytz module. Construct a timezone object based on this information.

Step 3: Manipulating and Attaching the Timezone

Use the pytz.timezone() method to create a timezone object representing the local timezone. However, it is important to note that daylight saving time (DST) complexities introduce ambiguities.

Step 4: Converting to UTC

To convert the datetime to UTC, apply the astimezone() method to the localized datetime. This method adjusts the datetime to UTC while accounting for DST and other timezone differences.

Step 5: Formatting the UTC String

Finally, use the strftime() method to format the UTC datetime into the desired string representation.

Example:

Consider converting the string "2001-2-3 10:11:12" from the local timezone "America/Los_Angeles" to UTC:

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)

print(utc_dt.strftime("%Y-%m-%d %H:%M:%S"))  # Output: 2001-02-03 18:11:12
Copy after login

The above is the detailed content of How Can I Convert Local Time Strings to UTC 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