Skip to content

Instantly share code, notes, and snippets.

@hmanicka
Last active April 30, 2021 15:22
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hmanicka/82834f2e0df016947730dbaf19d25c28 to your computer and use it in GitHub Desktop.
Save hmanicka/82834f2e0df016947730dbaf19d25c28 to your computer and use it in GitHub Desktop.
Flask-Admin: To update timestamp with timezone field with UTC
import pytz
class MyView(MyModelView):
# Display the time in user's local timezone on the List View
column_formatters =
dict(scheduledtime=lambda v,c,m,p: m.scheduledtime.replace(tzinfo=pytz.utc).astimezone(tz=pytz.timezone(config.LOCAL_TIMEZONE)))
# Display the time in user's timezone on the Edit View
def edit_form(self, obj):
form = self._edit_form_class(get_form_data(), obj=obj)
form.scheduledtime.data = form.scheduledtime.data.replace(tzinfo=pytz.utc).astimezone(tz=pytz.timezone(config.LOCAL_TIMEZONE))
return form
def on_model_change(self, form, model, is_created):
stime = request.form['scheduledtime']
# Convert the timestamp from user's local timezone to UTC before saving(..from Create/Edit Form)
local = pytz.timezone(config.LOCAL_TIMEZONE)
local_dt_nodst = local.localize(datetime.strptime(str(stime), "%Y-%m-%d %H:%M:%S"), is_dst=None)
isdst_now_in = lambda zonename: bool(local_dt_nodst.dst())
local_dt_dst = local.localize(datetime.strptime(str(stime), "%Y-%m-%d %H:%M:%S"), is_dst=isdst_now_in)
utc_dt = local_dt_dst.astimezone(pytz.utc)
model.scheduledtime = utc_dt.strftime("%Y-%m-%d %H:%M:%S")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment