This is an old revision of the document!


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.