Converting Python Datetime from Utc to Pst [Duplicate]

Using Python, I have a datetime object with the value (for example)

datetime(2021, 12, 28, 22, 31, tzinfo=tzutc())

This prints as

2021-12-28 22:31:00+00:00

How do I display that in US/Pacific?

I've seen references that use import pytz but I don't have that library available.

ANSWER: Even though it isn't the checked answer, I like the response by @jfs

from datetime import datetime, timezone

def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)

Output:

orig: 2021-12-28 22:31:00+00:00
after utc_to_local: 2021-12-28 14:31:00-08:00

At this time I am in PST and the offset from UTC is 8 hours

1

If you're using python 3.9+ you can use the built-in zoneinfo:

from zoneinfo import ZoneInfo
from dateutil.tz import tzutc
from datetime import datetime

date = datetime(2021, 12, 28, 22, 31, tzinfo=tzutc())
date = date.astimezone(ZoneInfo('US/Pacific'))
2021-12-28 14:31:00-08:00
1
Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest