0

I am using django/python

How do I convert pytz timezone string such as 'Asia/Kuala_Lumpur' to offset information ('+0800' or '80').

I am not able to find the exact function here:https://docs.djangoproject.com/en/3.1/topics/i18n/timezones/

I would like to use it in moment.js like this: Format date in a specific timezone

so the question is: 'Asia/Kuala_Lumpur' --> convert to ---> '+0800'

Axil
  • 3,606
  • 10
  • 62
  • 136
  • The problem is that a timezone is not just an offset. It comes with a set of rules like daylight saving time, the dates when to move between DST, etc. and a history of changes in the past. – Willem Van Onsem Nov 18 '20 at 23:52

1 Answers1

0

A timezone is not an offset. It is a set of rules how to calculate the offset for a given datetime. This means the current rules for example about daylight saving time (DST), and the historical ones where (small) changes have been made to the calendar.

You can determine the offset of the current datetime (or some other datetime) with:

>>> import pytz
>>> from datetime import datetime
>>> pytz.timezone('Asia/Kuala_Lumpur').localize(datetime.utcnow()).strftime('%z')
'+0800'

For example for Brussels time, two different timestamps can give two different offsets:

>>> tz = pytz.timezone('Europe/Brussels')
>>> tz.localize(datetime.utcnow()).strftime('%z')
'+0100'
>>> tz.localize(datetime(2020,5,1)).strftime('%z')
'+0200'

or for example Pyongyang changed the timezone on May 4th, 2018:

>>> pytz.timezone('Asia/Pyongyang').localize(datetime(2018,5,4)).strftime('%z')
'+0830'
>>> pytz.timezone('Asia/Pyongyang').localize(datetime(2018,5,5)).strftime('%z')
'+0900'

You thus can not simply map a timezone on an offset.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555