Created
December 2, 2013 19:34
-
-
Save abg/7756037 to your computer and use it in GitHub Desktop.
Decode raw MySQL 5.6 datetime data
This file contains hidden or 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 ctypes | |
| import datetime | |
| c_uint64 = ctypes.c_uint64 | |
| class MySQLDT(ctypes.BigEndianStructure): | |
| _fields_ = [ | |
| ("sign", c_uint64, 1), | |
| ("yearmonth", c_uint64, 17), | |
| ("day", c_uint64, 5), | |
| ("hour", c_uint64, 5), | |
| ("minute", c_uint64, 6), | |
| ("second", c_uint64, 6) | |
| ] | |
| @property | |
| def year(self): | |
| return self.yearmonth // 13 | |
| @property | |
| def month(self): | |
| return self.yearmonth % 13 | |
| def as_datetime(self): | |
| return datetime.datetime(year=self.year, | |
| month=self.month, | |
| day=self.day, | |
| hour=self.hour, | |
| minute=self.minute, | |
| second=self.second) | |
| @classmethod | |
| def from_bytes(cls, data): | |
| instance = cls() | |
| fit = min(len(data), ctypes.sizeof(instance)) | |
| ctypes.memmove(ctypes.addressof(instance), data, fit) | |
| return instance | |
| # encoded information for 1980-01-01 12:34:56 | |
| # extracted from the defaults buffer of a sample .frm file | |
| raw = '\x99#B\xc8\xb8' | |
| dt = MySQLDT.from_bytes(raw) | |
| print dt.as_datetime() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment