Example Using a Python Standard Library Module

Problem Definition

In this example we want to calculate a result based on a specific time range for an expression input. We set a supply voltage to zero within prescribed time ranges.

Expression

To solve this, we create the following Python expression:
0 if (SupplyVoltage.timestamp.astimezone().time() >= datetime.time(18) and 
SupplyVoltage.timestamp.astimezone().time() <= datetime.time(20, 30)) else 
SupplyVoltage.value
Python DatatypeNameDescription
Expression InputsSingleFloatSupplyVoltageRepresents the value we wish to transform.
Expression Resultdatetime Not Applicable Represents the resulting supply voltage, set to zero in the prescribed time ranges.

Python Modules to Import for this Expression

datetime module. This module is shipped with Historian.

Constructing the JSON

Using the created expression, we construct the following JSON:
{
 "imports":["datetime"],
 "script":"0 if (SupplyVoltage.timestamp.astimezone().time() >= datetime.time(18) and 
SupplyVoltage.timestamp.astimezone().time() <= datetime.time(20, 30)) else 
SupplyVoltage.value","parameters":[
  {   
  "name":" SupplyVoltage",
  "source":{"address":"Simulation00001", "dataType":"SingleFloat"}
  }
 ]
}

Note that the address parameter is stipulated in the context of the chosen collector, which must be on the list of collectors supporting Python Expression Tags. In this example, we have used the Simulation Collector. Your collector might use a different source address.

We then transform the above into a minified JSON string:
{"imports":["datetime"],"script":"0 if (SupplyVoltage.timestamp.astimezone().time() >= datetime.time(18) and 
SupplyVoltage.timestamp.astimezone().time() <= datetime.time(20, 30)) else 
SupplyVoltage.value","parameters":[{"name":"SupplyVoltage","source":
{"address":"Simulation00001","dataType":"SingleFloat"}}]}

Adding the Expression Tag to Historian

For this example, we choose to add a Python Expression tag to the Historian using the Historian Excel Add-In. (We could also have added the tag via the File Collector to import a CSV file.)

Ensure the following for your Python Expression Tag:
  • The CalcType is set to PythonExpr.
  • The SourceAddress contains the JSON configuration.

  • The CollectorName is set to the name of the chosen collector, which must be on the list of collectors supporting Python Expression Tags. Your collector might be called by a different name.
Otherwise, the tag is added in exactly the same way as for a regular tag.