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.

1

1 Answer 1

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'))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this works for me. Good to see that I can include information about timezone. :)
@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.
You're right but good to know before I get in trouble one more time! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.