Skip to content
Snippets Groups Projects
serializers.py 2.09 KiB
Newer Older
  • Learn to ignore specific revisions
  • import datetime
    
    
    # cf. https://stackoverflow.com/questions/30313243/messagepack-and-datetime
    def decode_datetime(obj):
        if '__datetime__' in obj.keys():
    
            tmp = datetime.datetime.strptime(obj["as_str"], "%Y-%m-%dT%H:%M:%S.%fZ")
            output = pytz.timezone('UTC').localize(tmp)
    
        elif '__date__' in obj.keys():
    
            output = datetime.datetime.strptime(obj["as_str"], "%Y-%m-%d")
    
    
    # cf. https://stackoverflow.com/questions/30313243/messagepack-and-datetime
    def encode_datetime(obj):
        if isinstance(obj, datetime.datetime):
    
    
            if obj.tzinfo is None:
                tmp1 = pytz.timezone("Europe/Paris").localize(obj)
            else:
                tmp1 = obj
    
            tmp2 = tmp1.astimezone(pytz.UTC)
    
            return {'__datetime__': True, 'as_str': tmp2.strftime("%Y-%m-%dT%H:%M:%S.%fZ")}
    
    
        if isinstance(obj, datetime.date):
    
            return {'__date__': True, 'as_str': obj.strftime("%Y-%m-%d")}
    
        # if isinstance(obj, Decimal):
        #     return float(obj)
        return obj
    
    
    
    if __name__ == '__main__':
    
        import pytz
    
        print('DATETIME WITHOUT TIMEZONE')
        datetime_without_timezone = datetime.datetime.now()
        print("Original:", datetime_without_timezone)
    
        encoded = encode_datetime(datetime_without_timezone)
        print("Encoded:", encoded)
    
        decoded = decode_datetime(encoded)
        print("Decoded:", decoded)
    
    
        print('')
        print('DATETIME WITH TIMEZONE')
        # datetime_with_timezone = datetime.datetime.now()
        tmp = pytz.timezone("Europe/Paris").localize(datetime.datetime.now())
        datetime_with_timezone = tmp.astimezone(pytz.timezone('America/New_York'))
        print(datetime_with_timezone)
    
        print("Original:", datetime_with_timezone)
    
        encoded = encode_datetime(datetime_with_timezone)
        print("Encoded:", encoded)
    
        decoded = decode_datetime(encoded)
        print("Decoded:", decoded)
    
    
        print('')
        print('DATE')
        date = datetime.date(2019, 3, 10)
        print("Original:", date)
    
        encoded = encode_datetime(date)
        print("Encoded:", encoded)
    
        decoded = decode_datetime(encoded)
        print("Decoded:", decoded)