Created
November 5, 2012 14:58
-
-
Save jrdmcgr/4017583 to your computer and use it in GitHub Desktop.
timezone validator
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
class LocalDateTime(formencode.FancyValidator): | |
""" This class is a formencode validator that will localize a date-time. | |
By default python date-time objects don't have any time zone information | |
associated with them, but they provide abstract support for time zones. | |
The pytz module provides concrete timezones to use with date-time objects. | |
This class will ensure that all dates have a timezone associated with them. | |
It will wite dates to the DB with the UTC time zone; it will convert dates | |
read from the DB to the client's local time zone defined in their config | |
file. | |
""" | |
# This time zone should be read from the client's config file. | |
# I'm just faking it for now. | |
tz = 'US/Eastern' | |
timezone = pytz.timezone(tz) | |
utc = pytz.UTC | |
def _to_python(self, value, state): | |
""" This method will transform the value before it gets read from the DB. | |
""" | |
if value.tzinfo: | |
return value.astimezone(self.timezone) | |
else: | |
return self.utc.localize(value).astimezone(self.timezone) | |
def _from_python(self, value, state): | |
""" This method will transform the value before it gets written to the DB. | |
""" | |
return self.timezone.localize(value).astimezone(self.utc) | |
# Use this validator in our models like so | |
class ProposalStepAction(SQLObject): | |
proposalStep = ForeignKey('ProposalStep') | |
user = ForeignKey('User') | |
created = DateTimeCol(default=None, validator=LocalDateTime) | |
modified = DateTimeCol(default=None, validator=LocalDateTime) | |
opened = DateTimeCol(default=None, validator=LocalDateTime) | |
signature = DateTimeCol(default=None, validator=LocalDateTime) | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment