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...
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
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