Controlling Simulation Start and Stop Time
Example file: docs/examples/api/example_sim_start_stop.py
Managing simulation time is one of the fundamental tasks in running a time-series simulation; this example walks through the how to control the start and stop time of the simulation, using Python's "datetime" library to do the heavy lifting for any time math.
GridLAB-D™ defines the simulation start and stop time inside the model file itself inside the "clock" object. This is a special object and isn't accessible via the normal object APIs (which we'll get to later) but instead uses a few dedicated APIs: get_starttime(), set_starttime(), get_toptime(), and set_stoptime(). These methods work exactly as you might guess based on their names, allowing you to get and set the start- and stop-time of the simulation. The values returned and accepted by these methods are ISO 8601 strings. Not by accident at all, Python's "datetime" library can convert these strings into datetime objects and convert datetime objects into these strings.
from datetime import datetime
starttime = datetime.fromisoformat(gld.get_starttime())
stoptime = datetime.fromisoformat(gld.get_stoptime())
gld.set_starttime(starttime.isoformat())
gld.set_stoptime(stoptime.isoformat())
The use of Python datetime objects avoids any of the common pitfalls when doing time-related string formatting or math. In this example, after getting the start and stop time into datetime objects, manipulating the start and stop time of the simulation becomes easy.
old_sim_duration = stoptime - starttime
new_sim_duration = old_sim_duration + timedelta(hours=1)
sim_duration_half = new_sim_duration / 2
calc_starttime = datetime.isoformat(starttime - sim_duration_half)
calc_stoptime = datetime.isoformat(stoptime + sim_duration_half)
gld.set_starttime(calc_starttime.isoformat())
gld.set_stoptime(calcstoptime.isoformat())
After adjusting these simulation times, we can just run the simulation directly by calling run(). And, as a bonus, it is also possible pass in new simulation start and/or stop times directly without first calling set_starttime() and set_stoptime(): gld.run(start_time=calc_starttime, stop_time=calc_stoptime).