Home > Backend Development > Python Tutorial > How to Convert a Local Time String to UTC in Python?

How to Convert a Local Time String to UTC in Python?

Susan Sarandon
Release: 2024-12-01 03:40:09
Original
116 people have browsed it

How to Convert a Local Time String to UTC in Python?

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")
Copy after login

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!

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