0

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

Jab
  • 26,853
  • 21
  • 75
  • 114
Gamsner
  • 117
  • 1
  • 9

2 Answers2

1

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)
Paul
  • 10,381
  • 13
  • 48
  • 86
1

The astimezone() method shown by Paul will adjust the date and time to match the new timezone. This is usually what you want. For example, if the timestamp you have is UTC, and you want to convert it to UTC+1 (or any other timezone), then you need to add an hour (or do some other arithmetic), which astimezone() does for you. It also takes care of daylight saving time or summer time, as well as numerous more substantial timezone irregularities.

However, sometimes this is not what you want. For example, if you have a UTC+1 timezone which is incorrectly labeled as UTC, then astimezone() will add an hour, producing a UTC+2 datetime which is incorrectly labeled UTC+1. If that describes your problem, then you should use the replace() method instead of astimezone(). This will simply "relabel" the timezone without doing any conversion arithmetic. For example, it will convert 14:00 UTC to 14:00 UTC+1. This is most useful in cases where you have a timestamp with no timezone information, or a parser that isn't smart enough to understand the timezone information given.

(You need to know which of these two problems you have. It is not possible to automatically determine whether your datetime object has the "right" timezone information, because Python cannot guess your intentions.)

Kevin
  • 28,963
  • 9
  • 62
  • 81