Newer
Older
# 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)
output = datetime.datetime.strptime(obj["as_str"], "%Y-%m-%d")
output = obj
return output
# 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")}
return {'__date__': True, 'as_str': obj.strftime("%Y-%m-%d")}
# if isinstance(obj, Decimal):
# return float(obj)
return obj
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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)