Helpful Functions

Below are a couple of utility functions that might be useful when developing drivers.

Timezone Conversion

Assuming you have a 'pytz' object called tz in your class that contains the timezone that is considered 'local' for your data source, you can use the following functions…

def utcToLocal(self,dt):
        if isinstance(dt,str):
            if '.' in dt:
                dt = datetime.strptime("%Y-%m-%d %H:%M:%S.%f",pytz.utc)
            else:
                dt = datetime.strptime("%Y-%m-%d %H:%M:%S",pytz.utc)            
 
        if dt.tzinfo is None:
            dt = dt.replace(tzinfo = pytz.utc)
 
        if self.timezone == "utc":
            return dt        
 
        lt = dt.astimezone(self.tz)        
        return lt
 
    def localToUTC(self,dt):
 
        if isinstance(dt,str):
            if '.' in dt:
                dt = datetime.strptime("%Y-%m-%d %H:%M:%S.%f")
            else:
                dt = datetime.strptime("%Y-%m-%d %H:%M:%S")
 
 
        if dt.tzinfo is None:
            dt = self.tz.localize(dt)
 
        if self.timezone == "utc":
            return dt        
 
        lt = dt.astimezone(pytz.utc)
        return lt
 
 

These two functions take the passed datetime (converting it from a string if required) and converts it between either UTC and the data-sources local time, or the data-sources local time and UTC.

Event Cleanup

Most Python objects can't be converted directly into JSON - this code converts each of the values in your dictionary to strings to make sure they can be sent to the ARDI server.

Note that it also does the job of converting Python datetime objects to both local and UTC versions (assuming your class has a 'tz' variable and is using the datetime functions detailed above).

#Convert to strings whevever possible
keys = list(dct.keys())
for d in keys:
    #Convert dates
    if isinstance(dct[d],datetime.datetime):
 
        #Make local and UTC versions of dates. All raw dates should be UTC.
        if self.timezone != "utc":
            dct[d + "_local"] = dct[d].strftime("%Y-%m-%d %H:%M:%S")
            dct[d + "_utc"] = self.localToUTC(dct[d]).strftime("%Y-%m-%d %H:%M:%S")
            dct[d] = dct[d + "_utc"]
        else:
            dct[d] = dct[d].strftime("%Y-%m-%d %H:%M:%S")
    else:
        dct[d] = str(dct[d])