Display correct Local Time with DST Change

There’s a good write up of this problem at Python: Timezone and Daylight savings | by Bao Nguyen | Medium

The clocks change here in the UK this weekend. Here’s a demo using the pytz module on the server to show two dates either side of the change:

https://anvil.works/build#clone:TGQUI6QTT466P6M2=BAEM53SVC4LM2WKRQYHZ6GHY

Server module:

import anvil.server
import datetime as dt
import pytz


@anvil.server.callable
def get_dates(timezone):
    tz = pytz.timezone(timezone)
    noon_today = dt.datetime(2021, 10, 28, 12) # DST still in place
    noon_next_monday = dt.datetime(2021, 11, 1, 12) # After the clocks go back - same as UTC
    dates = [tz.localize(date) for date in (noon_today, noon_next_monday)]
    print(f"server side: {dates}")
    return dates

Client module:

import anvil.server
import datetime as dt

dates = anvil.server.call('get_dates', "Europe/London")
print(f"client side: {dates}")

Gives:

server side: [datetime.datetime(2021, 10, 28, 12, 0, tzinfo=<DstTzInfo 'Europe/London' BST+1:00:00 DST>), datetime.datetime(2021, 11, 1, 12, 0, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)]
client side: [datetime.datetime(2021, 10, 28, 12, 0, tzinfo=<anvil.tz.tzoffset (1 hours)>), datetime.datetime(2021, 11, 1, 12, 0, tzinfo=<anvil.tz.tzoffset (0 hours)>)]
3 Likes