How to convert local time string to UTC with Python?

Sometimes, we want to convert local time string to UTC with Python.

In this article, we’ll look at how to convert local time string to UTC with Python.

How to convert local time string to UTC with Python?

To convert local time string to UTC with Python, we can use the astimezone method.

For instance, we write

from datetime import datetime   
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2022-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)

to call pytz.timezone to get the time zone.

Then we parse our datetime string as a naive datetime with

naive = datetime.strptime("2022-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")

Then we convert it to a local time with

local_dt = local.localize(naive, is_dst=None)

And then we convert it to UTC with

utc_dt = local_dt.astimezone(pytz.utc)

Conclusion

To convert local time string to UTC with Python, we can use the astimezone method.