0

I have incoming strings that are UTC dates in ISO format like,

2021-11-21T12:16:42Z

I wish to convert these dates into PST and then subtract 12 hours from it.

import datetime
time_list_utc=2021-11-21T12:16:42Z
time_list_pst=time_list_utc.convert(pst)
print(time_list_pst-8hours)

I am new to datetime manipulation so any input is greatly appreciated

Cyber_Tron
  • 299
  • 1
  • 6
  • 17
  • Does this answer your question? [need to convert UTC (aws ec2) to PST in python](https://stackoverflow.com/questions/8809765/need-to-convert-utc-aws-ec2-to-pst-in-python) – not_speshal Nov 22 '21 at 20:43
  • Does this answer your question? [Display the time in a different time zone](https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone) – FObersteiner Nov 23 '21 at 06:41
  • see also: [parse ISO format's 'Z' with datetime.fromisoformat](https://stackoverflow.com/a/62769371/10197418) – FObersteiner Nov 23 '21 at 06:42

1 Answers1

1

Use datetime, tzinfo and timedelta modules since Python 3.9:

from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

s = '2021-11-21T12:16:42Z'

# Convert to datetime (UTC)
dt_utc = datetime.strptime(utc, "%Y-%m-%dT%H:%M:%S%z")

# Convert to PST
dt_pst = dt_utc.astimezone(ZoneInfo('US/Pacific'))

# Subtract 12 hours
dt = dt_pst - timedelta(hours=12)

Output:

>>> dt
datetime.datetime(2021, 11, 20, 16, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))

>>> dt_pst
datetime.datetime(2021, 11, 21, 4, 16, 42, tzinfo=zoneinfo.ZoneInfo(key='US/Pacific'))

>>> dt_utc
datetime.datetime(2021, 11, 21, 12, 16, 42, tzinfo=datetime.timezone.utc)
Corralien
  • 109,409
  • 8
  • 28
  • 52