0

I have a string datetime as - '2022-12-07T13:30:14+00:00' and '2022-12-07T13:30:07.697000+00:00'

How can I convert the + timezone to UTC time and get output in both the cases as - "2022-12-07T13:30:14.000Z" and '2022-12-07T13:30:07.697Z'

Please help.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
deepu2711
  • 59
  • 1
  • 7

1 Answers1

2

You can make use of fromisoformat and isoformat. If you have mixed UTC offsets, convert to UTC with astimezone.

from datetime import datetime, timezone

strings = ['2022-12-07T13:30:14+00:00', '2022-12-07T13:30:07.697000+00:00',
           '2022-12-07T13:30:14+01:00', '2022-12-07T13:30:07.697000+05:30']

for s in strings:
    print(
        datetime.fromisoformat(s)
            .astimezone(timezone.utc) # to UTC if input has other offset
            .isoformat(timespec="milliseconds") # consistent precision in output
            .replace("+00:00", "Z") # no "standard-way" to get Z for UTC
        )
    
# 2022-12-07T13:30:14.000Z
# 2022-12-07T13:30:07.697Z
# 2022-12-07T12:30:14.000Z
# 2022-12-07T08:00:07.697Z 
FObersteiner
  • 22,500
  • 8
  • 42
  • 72