0

I have a datetime object saved in a django field. I query it, change the timezone and print it, this is the code and what I get:

Code:

    print("event.date_start: %s" % event.date_start)
    print("event.date_start.hour: %s" % event.date_start.hour)
    print("event.date_start.tzinfo: %s" % event.date_start.tzinfo)

    user_timezone = pytz.timezone("ETC/"+logged_user_profile.timezone)
    print("user_timezone: %s" % user_timezone)

    event_user_timezone = event.date_start.astimezone(user_timezone)  # HERE
    print("event_user_timezone: %s" % event_user_timezone)
    print("event_user_timezone.hour: %s" % event_user_timezone.hour)

Prints:

event.date_start: 2020-11-17 18:00:00+00:00
event.date_start.hour: 18
event.date_start.tzinfo: UTC
user_timezone: Etc/GMT-5
event_user_timezone: 2020-11-17 23:00:00+05:00
event_user_timezone.hour: 23

As you can see, the initial tzinfo is UTC, then I use astimezone to actualize it and change it to ETC/GMT-5. But the time changes to GMT+5. Don't understand. If you need extra info plz let me know.

Alejandro Veintimilla
  • 10,743
  • 23
  • 91
  • 180
  • 1
    What's the value of `logged_user_profile.timezone`? If you're already using `pytz` you can use a timezone name like `America/Guayaquil` instead of `GMT-5` because it will also handle DST. – Ionut Ticus Nov 12 '20 at 18:07
  • @Ionut Ticus the value of `logged_user_profile.timezone` is GMT-5 . Thanks for the DST recommendation – Alejandro Veintimilla Nov 12 '20 at 18:29
  • that's just how these `etc/gmt` UTC offsets work - e.g. GMT-5 means "this time would be GMT if you subtract 5 hours (so the time would show up as UTC +5). by the way, this is not related to pytz. it's the same if you obtain the time zone from dateutil or zoneinfo. – FObersteiner Nov 12 '20 at 18:48
  • @MrFuppes That would be a pytz bug cause I live in GMT-5 and it is 5 hours behind UTC https://time.is/GMT-5 . – Alejandro Veintimilla Nov 12 '20 at 18:54
  • 1
    No. That's a different thing - e.g. my current UTC offset is CET/UTC+1, but the corresponding etc/gmt would be etc/gmt**-1**. And again, these "etc" time zones aren't an invention of pytz. My bottom line would be: it's just confusing, don't use them. As @IonutTicus commented, better use a propper IANA time zone name to localize a datetime object. Even better: don't use pytz anymore, it's deprecated with Python 3.9 - [example](https://stackoverflow.com/a/63628816/10197418). – FObersteiner Nov 12 '20 at 18:58
  • some more insights can be gained in Paul Eggert's [tz repo, in /etcetera](https://github.com/eggert) – FObersteiner Nov 12 '20 at 19:10

0 Answers0