From 2a86abe66ebd6d49a427987c6cd6d71c486e0f18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Wed, 29 Jun 2016 16:49:19 +0200 Subject: [PATCH] Datetimes are now returned as timezone-aware. Timezone is hardcoded as UTC for now, as Pillar always returns UTC times. --- pillarsdk/utils.py | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/pillarsdk/utils.py b/pillarsdk/utils.py index 3c60c6a..75c3921 100644 --- a/pillarsdk/utils.py +++ b/pillarsdk/utils.py @@ -1,8 +1,10 @@ import json import re import sys -from datetime import datetime +import datetime +import time from contextlib import closing + import requests try: @@ -27,7 +29,7 @@ class PillarJSONEncoder(json.JSONEncoder): # Late import to prevent circular references. from .resource import Resource - if isinstance(obj, datetime): + if isinstance(obj, datetime.datetime): return obj.isoformat(' ') if isinstance(obj, Resource): return obj.to_dict() @@ -104,6 +106,24 @@ def merge_dict(data, *override): return result +ZERO = datetime.timedelta(0) + + +class UTC(datetime.tzinfo): + """UTC""" + + def utcoffset(self, dt): + return ZERO + + def tzname(self, dt): + return "UTC" + + def dst(self, dt): + return ZERO + +utc = UTC() + + def convert_datetime(item): """Starting from a JSON object, find and replace the _create and _updated keys with actual datetime objects. @@ -113,7 +133,9 @@ def convert_datetime(item): for k in keys: # Check if the key is in the document if k in item: - item[k] = datetime.strptime(item[k], "%a, %d %b %Y %H:%M:%S %Z") + parsed = time.strptime(item[k], "%a, %d %b %Y %H:%M:%S %Z") + as_utc = datetime.datetime(*parsed[0:6], tzinfo=utc) + item[k] = as_utc return item