0
dt = "2021-06-10T10:56:58.189+0200"

is my timestamp, which i want to convert into a datetime representation. I use following code to do this:

d = dateutil.parser.parse(dt)

But my output looks like this:

2021-06-10 10:56:58.189000+02:00

Not much has changed. How can I include the information about the timezone in my newly created datetime object. I tried out a few more things from the documentation but can not work it out on my own..

Thanks in advance.

yannickhau
  • 385
  • 1
  • 13
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jun 10 '21 at 10:08

1 Answers1

1

note that +0200 is a UTC offset, not a time zone ("America/Los_Angeles" is a time zone for example). If you wish to set a specific time zone, you can do it like

from datetime import datetime
from zoneinfo import ZoneInfo

# you can do the parsing with the standard lib:
s = "2021-06-10T10:56:58.189+0200"
dt = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%f%z")

# now set a time zone:
dt_tz = dt.astimezone(ZoneInfo("Europe/Berlin"))
                      
print(dt_tz) # __str__ gives you ISO format 
# 2021-06-10 10:56:58.189000+02:00

print(dt_tz.strftime("%Y-%m-%dT%H:%M:%S %Z")) # custom format
# 2021-06-10T10:56:58 CEST

print(repr(dt_tz)) # object representation; __repr__
# datetime.datetime(2021, 6, 10, 10, 56, 58, 189000, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Thanks, this works for me. Good to see that I can include information about timezone. :) – yannickhau Jun 10 '21 at 10:25
  • @yannickhau that's what the `tzinfo` attribute of the datetime class is for ;-) Be aware though that you can unambiguously infer a UTC offset from a given date/time + time zone *- but not vice versa*. Multiple (geographic) time zones might share the same UTC offset at a given point in time. – FObersteiner Jun 10 '21 at 10:30
  • You're right but good to know before I get in trouble one more time! ;) – yannickhau Jun 10 '21 at 10:37