0

I need to have "2020-07-29 10:27:08+02:00" in this format "2020-07-29T08:27:16.494Z" (I know the value of both strings is different, it is only about the format).

I tried this so far:

dt = datetime.strptime(realTimeStamp,"%d/%b/%Y:%H:%M:%S%z")
print(dt.date()) # results to 2020-07-27

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
WorkoutBuddy
  • 609
  • 9
  • 23
  • 1
    It's almost the same format (ISO8601), for different timezone offsets. The first is in +2:00, the second is UTC. What you really ask is how to convert between timezone offsets. There are several similar questions – Panagiotis Kanavos Jul 29 '20 at 08:59
  • Check [this one](https://stackoverflow.com/questions/10997577/python-timezone-conversion) or [this](https://stackoverflow.com/questions/4563272/convert-a-python-utc-datetime-to-a-local-datetime-using-only-python-standard-lib). Once you parse the string into a date you can use `astimezone` to convert from one timezone to another – Panagiotis Kanavos Jul 29 '20 at 09:04
  • @PanagiotisKanavos: if you look at the details of the desired output format, Python standard methods (e.g. `datetime.isoformat()`) neither give milliseconds nor 'Z' for zulu time (UTC). – FObersteiner Jul 29 '20 at 13:18

1 Answers1

1

With standard methods, you don't get milliseconds and 'Z', so we need to improvise. Here's a way to do it.

from datetime import datetime, timezone

s = "2020-07-29 10:27:08.494+02:00"

# parse to datetime object including the UTC offset and convert to UTC
dt = datetime.fromisoformat(s).astimezone(timezone.utc)

# format to string, excluding microseconds and UTC offset
out = dt.strftime('%Y-%m-%dT%H:%M:%S')
# add the microseconds, rounded to milliseconds
out += f"{dt.microsecond/1e6:.3f}".lstrip('0')
# add UTC offset, Z for zulu/UTC - we know it's UTC from conversion above
out += 'Z'

This will give you

print(out)
>>> 2020-07-29T08:27:08.494Z
FObersteiner
  • 22,500
  • 8
  • 42
  • 72