Search code examples
pythonpython-dateutil

Change timestamp from dateutil from utc to not utc


What exists

import datetime
import dateutil.parser
import time

timestamp = dateutil.parser.parse(response["body"]["inserted_at"])

Whats the problem
This timestamp is UTC, but it should be UTC+1, or TimeZone Europe,Zurich

Question
What shall I add to the existing code to have timestampas Europe,Zurich, and no moreUTC`?

Thanks in advance


Solution

  • You want to use the astimezone method of datetime.datetime. If you have a datetime in any time zone (e g. UTC) and want it in another zone, you use dt_new_tz = dt_old_tz.astimezone(new_tz)

    In this case, you want:

    from dateutil import tz
    zurich_tz = tz.gettz("Europe/Zurich")
    new_ts = timestamp.astimezone(zurich_tz)