-1

I want to convert a time given from user to UTC/RFC 3339 format. For example, if they gave the string 2022-07-20 1:09:51 I want it to print it 2022-07-20T20:08:51Z. I got how to do it if given the posix time but dont understand how to do it given a string in the above format

Users in pacific time zone

1 Answers1

0

Parse the input, set the timezone, convert to UTC, then format the output.

from datetime import datetime
from zoneinfo import ZoneInfo
# May need to "pip install tzdata" for latest timezone support.
# It is used by ZoneInfo.  See https://docs.python.org/3/library/zoneinfo.html

UTC = ZoneInfo('UTC')
LOCAL = ZoneInfo('US/Pacific')

s = '2022-07-20 1:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')
local = dt.replace(tzinfo=LOCAL)
utc = local.astimezone(UTC)
print('naive ',dt)
print('local ',local)
print('UTC   ',utc)
print('ISO   ',utc.isoformat())
print('custom',utc.strftime('%Y-%m-%dT%H:%M:%SZ'))

Output:

naive  2022-07-20 01:09:51
local  2022-07-20 01:09:51-07:00
UTC    2022-07-20 08:09:51+00:00
ISO    2022-07-20T08:09:51+00:00
custom 2022-07-20T08:09:51Z

If you want PM as you implied use either:

s = '2022-07-20 1:09:51pm'
dt = datetime.strptime(s, '%Y-%m-%d %I:%M:%S%p')

or

s = '2022-07-20 13:09:51'
dt = datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

To get a final result of:

custom 2022-07-20T20:09:51Z
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251