diff options
author | Diego Elio Pettenò <flameeyes@flameeyes.eu> | 2018-01-01 12:51:23 +0100 |
---|---|---|
committer | Diego Elio Pettenò <flameeyes@flameeyes.eu> | 2018-01-01 12:51:23 +0100 |
commit | cfbf51d6a090626accfc8437f5bd586112178a34 (patch) | |
tree | 1fdabfbc3a7d52331eee506a4975d83f233b28b6 /glucometerutils/support/construct_extras.py | |
parent | otultraeasy: rewrite using construct for parsing. (diff) | |
download | glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar.gz glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar.bz2 glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar.lz glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar.xz glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.tar.zst glucometerutils-cfbf51d6a090626accfc8437f5bd586112178a34.zip |
Diffstat (limited to '')
-rw-r--r-- | glucometerutils/support/construct_extras.py | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/glucometerutils/support/construct_extras.py b/glucometerutils/support/construct_extras.py new file mode 100644 index 0000000..cb42105 --- /dev/null +++ b/glucometerutils/support/construct_extras.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +"""Extra classes for Construct.""" + +__author__ = 'Diego Elio Pettenò' +__email__ = 'flameeyes@flameeyes.eu' +__copyright__ = 'Copyright © 2018, Diego Elio Pettenò' +__license__ = 'MIT' + +import datetime + +import construct + +class Timestamp(construct.Adapter): + """Adapter for converting datetime object into timestamps. + + Take two parameters: the subcon object to output the resulting timestamp as, + and an optional epoch offset to the UNIX Epoch. + + """ + __slots__ = ["epoch"] + + def __init__(self, subcon, epoch=0): + super(Timestamp, self).__init__(subcon) + self.epoch = epoch + + def _encode(self, obj, context): + assert isinstance(obj, datetime.datetime) + epoch_date = datetime.datetime.utcfromtimestamp(self.epoch) + delta = obj - epoch_date + return int(delta.total_seconds()) + + def _decode(self, obj, context): + return datetime.datetime.utcfromtimestamp(obj + self.epoch) |