Last active
March 8, 2024 09:18
-
-
Save tachyondecay/2c1462eed197f879f0bf to your computer and use it in GitHub Desktop.
DateTime WTForms field that assumes input is in local time and converts to UTC for storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Requires Arrow package | |
class DateTimeWidget: | |
"""Widget for DateTimeFields using separate date and time inputs.""" | |
def __call__(self, field, **kwargs): | |
id = kwargs.pop('id', field.id) | |
date = time = '' | |
if field.data: | |
dt = arrow.get(field.data).to(current_app.config['TIMEZONE']) | |
date = dt.format('YYYY-MM-DD') | |
time = dt.format('HH:mm:ss') | |
date_params = html_params(name=field.name, id=id + '-date', value=date, **kwargs) | |
time_params = html_params(name=field.name, id=id + '-time', value=time, **kwargs) | |
return HTMLString('<input type="date" {}/><input type="time" {}/>'.format(date_params, time_params)) | |
class DateTimeLocalField(DateTimeField): | |
""" | |
DateTimeField that assumes input is in app-configured timezone and converts | |
to UTC for further processing/storage. | |
""" | |
widget = DateTimeWidget() | |
def process_formdata(self, valuelist): | |
current_app.logger.debug(valuelist) | |
if valuelist: | |
date_str = ' '.join(valuelist) | |
try: | |
self.data = arrow.get(date_str).replace(tzinfo=current_app.config['TIMEZONE']).to('UTC') | |
except arrow.parser.ParserError as e: | |
current_app.logger.warn('Invalid datetime value submitted: %s', e) | |
raise ValueError('Not a valid datetime value. Looking for YYYY-MM-DD HH:mm.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, this worked perfectly. I hope you don't mind if I use it! thank you