Categories
Python Answers

How to convert local time string to UTC with Python?

Spread the love

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 datetime and pytz modules.

For instance, we write:

from datetime import datetime
import pytz

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

We call pytz.timezone with the time zone string to create the local time zone object.

Then we convert a date and time string to a datetime object with datetime.strptime`.

Next, we call local.localize with the naive dattime to convert it to a local date time.

We set is_dst to None to make sure the time isn’t set to daylight saving time.

Then we call local_dt.astimezone with pytz.utc to get the UTC date time and assign it to utc_dt.

Therefore utc_dt is 2021-02-03 18:11:12+00:00.

Conclusion

To convert local time string to UTC with Python, we can use the datetime and pytz modules.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *