Major - P3
This is a followup to my mongodb-user post:
Please consider this patch for inclusion in the MongoDB Python driver.
A patch that implements a bson.tzinfo module attribute that allows the
user to work with naive local datetimes which the driver automatically
converts to and from the recommended UTC storage format.
Web applications run on the server but are viewed and controlled from
the client browser:
- Clients and servers are are often in different timezones.
- Clients expect to view and input localized datetimes.
- Frameworks such as Django work best with naive local datetimes.
- Typically the client's timezone is available to the server in login
Non-Web apps are also simplified by not having to perform manual local
to UTC conversions.
How it works
If the bson.tzinfo module attribute is set to a pytz timezone then:
- All naive datetimes feed to PyMongo are assumed to be in the
bson.tzinfo timezone and are automatically converted UTC before
being written to the database.
- All aware datetimes feed to PyMongo are automatically converted UTC
before being written to the database.
- All (UTC) datetimes read from a database with PyMongo are
automatically converted to aware datetimes in the bson.tzinfo
To set the timezone do something like this:
bson.tzinfo = pytz.timezone('Pacific/Auckland')
To revert to default PyMongo behavior:
bson.tzinfo = None
Most Linux distribution store the local Olson timezone name in
/etc/timezone – you can get a local tzinfo instance with something
- The attached patch is against PyMongo 1.9 (at Git commit b6b0e7d).
patch -p1 <pymongo-timezone-transparency.patch
- The patch includes both Python and CPython implementations.
- The implementation is not dependent on pytz (but the user will need
pytz to use the feature).
- I've also attached a simple standalone sanity checker test