Created
September 22, 2013 00:00
-
-
Save acdha/6655391 to your computer and use it in GitHub Desktop.
First pass at making Python's sqlite3 module not choke on timestamps with timezones
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
import datetime | |
import sqlite3 | |
def tz_aware_timestamp_adapter(val): | |
datepart, timepart = val.split(b" ") | |
year, month, day = map(int, datepart.split(b"-")) | |
if b"+" in timepart: | |
timepart, tz_offset = timepart.rsplit(b"+", 1) | |
if tz_offset == b'00:00': | |
tzinfo = datetime.timezone.utc | |
else: | |
hours, minutes = map(int, tz_offset.split(b':', 1)) | |
tzinfo = datetime.timezone(datetime.timedelta(hours=hours, minutes=minutes)) | |
else: | |
tzinfo = None | |
timepart_full = timepart.split(b".") | |
hours, minutes, seconds = map(int, timepart_full[0].split(b":")) | |
if len(timepart_full) == 2: | |
microseconds = int('{:0<6.6}'.format(timepart_full[1].decode())) | |
else: | |
microseconds = 0 | |
val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds, tzinfo) | |
return val | |
sqlite3.register_converter('timestamp', tz_aware_timestamp_adapter) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have the problem mentioned @ http://bugs.python.org/issue19065.
Note that this function will not work in python 2.X because datetime does not have timezone.