Explain Codes LogoExplain Codes Logo

How to convert local time string to UTC?

python
timezone-conversions
datetime-objects
python-3.9
Nikita BarsukovbyNikita Barsukov·Sep 4, 2024
TLDR

For quick local to UTC conversions, use the pytz package with Python's datetime. Parse your local time and its given timezone into a datetime object and convert to UTC:

from datetime import datetime import pytz # Turn a New Year's moment into a confusing time decoding puzzle... local_time = '2022-01-01 12:34:56' timezone = 'America/New_York' time_with_zone = datetime.strptime(local_time, '%Y-%m-%d %H:%M:%S') local_zone = pytz.timezone(timezone) time_with_zone = local_zone.localize(time_with_zone, is_dst=None) # Always play it safe with DST! utc_time = time_with_zone.astimezone(pytz.utc) print(utc_time.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Substitute local_time and timezone for your actual time and zone. Apply this code to print the corresponding UTC time.

Working with Timezone Conversions

To properly convert between different time zones, we need a deeper understanding of time itself. Let's get started!

Time awareness and DST

Convert time strings to timezone-aware datetime objects to factor in Daylight Saving Time (DST). Remember, DST could potentially steal an hour from your timestamp if disregarded!

Transforming local time strings

Python allows several methods to convert a time string:

  • datetime.strptime creates simplistic, timezone-naive datetime objects. It's old school but reliable.
  • dateutil.parser.parse allows flexible parsing and ISO 8601 formats. When you need flexibility in your timestamps!
  • datetime.fromisoformat provides a fast and easy ISO 8601 parsing (Python 3.6+), because who has the time to parse time strings manually?

Consistency is key

Avoid confusion across systems by storing timestamps in UTC, ideally. In a manner of speaking, if time's a river, UTC is our steady rock.

Python for timezone problems

Recent Python versions have improved timezone handling, making our lives easier. Python 3.9 introduced the zoneinfo module, a modern solution for handling tricky timezone problems.

Converting to UTC like a Pro

Gear up to tackle the quirks of UTC conversion with a smile (and a cup of coffee).

Precision is priceless

Gain precision by using astimezone() with care! Proper localization with pytz or zoneinfo is a lifebelt for risks associated with DST changes.

Understand the quirkiness of conversion functions

The functions .utcnow() and .utcfromtimestamp() don't consider DST, leaving them stunned twice a year!

Time arithmetic hacks

To manage time arithmetic, ideally use dateutil.relativedelta. It juggles with months and years much more gracefully than timedelta.

Time in databases

When handling databases, ensure timestamps are in UTC. Remember, time zones are like relatives at a holiday dinner; normalize them for everybody's sake!