title: Night flight time calculation: IndexError: invalid index to scalar variable
body: <p>I'm using vsimakhin's night time calculator (<a href="https://github.com/vsimakhin/night-time-calculator" rel="nofollow noreferrer">https://github.com/vsimakhin/night-time-calculator</a>) to calculate total night time flown during a flight given the departure and arrival locations and times. I am new to Python so i'm not sure what the issue is. I get the following error:</p>
  <pre><code>IndexError: invalid index to scalar variable
  </code></pre>
  <p>This is the code i'm using:</p>
  <pre><code>import sys
  import json
  import datetime
  import copy
  from skyfield import api
  from skyfield import almanac
  import nvector
  
  
  ui_fmt = &quot;%Y-%m-%d %H:%M&quot;
  
  
  def main():
      # arg format
      # XXXXTTTTYYYYTTTT[YYYYMMDD]
      input_string = sys.argv[1]
      departure_str = input_string[:4]
      departure_time = input_string[4:8]
      arrival_str = input_string[8:12]
      arrival_time = input_string[12:16]
  
      if(len(input_string) &gt; 16):
          flight_date = datetime.datetime.strptime(
              input_string[16:], '%Y%m%d').replace(tzinfo=datetime.timezone.utc)
      else:
          flight_date = datetime.datetime.utcnow().date()
  
      airports = json.load(open('airports.json'))
      departure = copy.copy(airports[departure_str])
      arrival = copy.copy(airports[arrival_str])
  
      # calculate distance
      L = calculate_distance(
          departure[&quot;lat&quot;],
          departure[&quot;lon&quot;],
          arrival[&quot;lat&quot;],
          arrival[&quot;lon&quot;]
      )
  
      # calculate flight time
      departure[&quot;time&quot;] = datetime.datetime.strptime(
          f&quot;{flight_date.strftime('%Y%m%d')}{departure_time}&quot;,
          '%Y%m%d%H%M').replace(tzinfo=datetime.timezone.utc)
  
      arrival[&quot;time&quot;] = datetime.datetime.strptime(
          f&quot;{flight_date.strftime('%Y%m%d')}{arrival_time}&quot;,
          '%Y%m%d%H%M').replace(tzinfo=datetime.timezone.utc)
  
      flight_time = arrival[&quot;time&quot;] - departure[&quot;time&quot;]
      if flight_time.days &lt; 0:
          flight_time += datetime.timedelta(days=1)
          arrival[&quot;time&quot;] += datetime.timedelta(days=1)
  
      print(f&quot;Departure: {departure_str} Time: {departure['time'].strftime(ui_fmt)} IATA: {departure['iata']} City: {departure['city']}&quot;)
      print(f&quot;Arrival:   {arrival_str} Time: {arrival['time'].strftime(ui_fmt)} IATA: {arrival['iata']} City: {arrival['city']}&quot;)
      print(f&quot;Distance:  {int(L)}nm Flight time: {flight_time}&quot;)
  
      # average airplane speed based on block time, kt
      Vplane = L / (flight_time.seconds / 3600)
  
      # get some sun parameters
      (departure[&quot;sunrise&quot;], departure[&quot;sunset&quot;]) = get_sun_data(departure[&quot;lat&quot;], departure[&quot;lon&quot;], departure[&quot;time&quot;])
      (arrival[&quot;sunrise&quot;], arrival[&quot;sunset&quot;]) = get_sun_data(arrival[&quot;lat&quot;], arrival[&quot;lon&quot;], arrival[&quot;time&quot;])
  
      print(f&quot;Departure Sunrise: {departure['sunrise'].strftime(ui_fmt)} Sunset: {departure['sunset'].strftime(ui_fmt)}&quot;)
      print(f&quot;Arrival   Sunrise: {arrival['sunrise'].strftime(ui_fmt)} Sunset: {arrival['sunset'].strftime(ui_fmt)}&quot;)
  
      if (departure[&quot;sunrise&quot;] &lt;= departure[&quot;time&quot;] &lt;= departure[&quot;sunset&quot;]) and (arrival[&quot;sunrise&quot;] &lt;= arrival[&quot;time&quot;] &lt;= arrival[&quot;sunset&quot;]):
          print(&quot;Full day flight&quot;)
          exit()
      elif (departure[&quot;sunrise&quot;] &lt;= departure[&quot;time&quot;] &lt;= departure[&quot;sunset&quot;]):
          print(&quot;Flight from day to night, night landing&quot;)
  
          x_point = meet_with_sun(departure, arrival, Vplane, &quot;sunset&quot;)
          nt = (arrival[&quot;time&quot;] - x_point[&quot;time&quot;]).seconds / 3600
  
      elif (arrival[&quot;sunrise&quot;] &lt;= arrival[&quot;time&quot;] &lt;= arrival[&quot;sunset&quot;]):
          print(&quot;Flight from night to day, day landing&quot;)
  
          x_point = meet_with_sun(departure, arrival, Vplane, &quot;sunrise&quot;)
          nt = (x_point[&quot;time&quot;] - departure[&quot;time&quot;]).seconds / 3600
  
      else:
          print(&quot;Full night time&quot;)
          nt = flight_time.seconds / 3600
  
      print(f&quot;Night time: {convert_time(nt)}&quot;)
  
  
  def meet_with_sun(departure, arrival, Vplane, target):
      max_iterations = 50
      max_diff_minutes = 0.5
      i = 0
      found_x = False
  
      start_point = copy.copy(departure)
      end_point = copy.copy(arrival)
  
      print(f&quot;Departure lat/lon: {start_point['lat']:.2f} {start_point['lon']:.2f} | Arrival lat/lon: {end_point['lat']:.2f} {end_point['lon']:.2f}&quot;)
      print(f&quot; lat    lon    dist   time on route     flt time  {target:17s}  diff (min)&quot;)
      while((i &lt; max_iterations) and not found_x):
          i += 1
  
          x_point = {}
          x_point[&quot;lat&quot;], x_point[&quot;lon&quot;] = get_midpoint(start_point[&quot;lat&quot;], start_point[&quot;lon&quot;], end_point[&quot;lat&quot;], end_point[&quot;lon&quot;])
  
          (x_point[&quot;sunrise&quot;], x_point[&quot;sunset&quot;]) = get_sun_data(x_point[&quot;lat&quot;], x_point[&quot;lon&quot;], departure[&quot;time&quot;])
          D = calculate_distance(departure[&quot;lat&quot;], departure[&quot;lon&quot;], x_point[&quot;lat&quot;], x_point[&quot;lon&quot;])
          flight_time = datetime.timedelta(hours=(D / Vplane))
          x_point[&quot;time&quot;] = departure[&quot;time&quot;] + flight_time
  
          diff = (x_point[&quot;time&quot;] - x_point[target])
          if diff.days &lt; 0:
              diff += datetime.timedelta(days=1)
              diff_m = - 24 * 60 + diff.seconds / 60
          else:
              diff_m = diff.seconds / 60
  
          print(f&quot;{x_point['lat']:6.2f} &quot;
                f&quot;{x_point['lon']:6.2f} &quot;
                f&quot;{D:7.2f} &quot;
                f&quot;{x_point['time'].strftime(ui_fmt):17s} &quot;
                f&quot;{convert_time(flight_time.seconds / 3600):10s}&quot;
                f&quot;{x_point[target].strftime(ui_fmt):17s} &quot;
                f&quot;{diff_m:7.2f}&quot;)
  
          if abs(diff_m) &gt;= max_diff_minutes:
              if diff_m &gt; 0:
                  start_point = copy.copy(start_point)
                  end_point = copy.copy(x_point)
              else:
                  start_point = copy.copy(x_point)
                  end_point = copy.copy(end_point)
          else:
              found_x = True
  
      return x_point
  
  
  def get_midpoint(lat1, lon1, lat2, lon2):
  
      points = nvector.GeoPoint(latitude=[lat1, lat2], longitude=[lon1, lon2], degrees=True)
      nvectors = points.to_nvector()
      n_EM_E = nvectors.mean()
      g_EM_E = n_EM_E.to_geo_point()
      lat, lon = g_EM_E.latitude_deg, g_EM_E.longitude_deg
  
      return lat[0], lon[0]
  
  
  def get_sun_data(lat, lon, flight_date):
      sky_fmt = &quot;%Y-%m-%dT%H:%M:%SZ&quot;
  
      ts = api.load.timescale()
      e = api.load('de421.bsp')
  
      sunrise = None
      sunset = None
  
      bluffton = api.Topos(lat, lon)
      # first get sunrise and sunset times
      t, y = almanac.find_discrete(ts.utc(flight_date.date()), ts.utc(flight_date.date() + datetime.timedelta(days=1)), almanac.sunrise_sunset(e, bluffton))
      for ti, yi in zip(t, y):
          if yi:
              sunrise = ti.utc_iso()
          else:
              sunset = ti.utc_iso()
  
      return (datetime.datetime.strptime(sunrise, sky_fmt).replace(tzinfo=datetime.timezone.utc) - datetime.timedelta(minutes=30),
              datetime.datetime.strptime(sunset, sky_fmt).replace(tzinfo=datetime.timezone.utc) + datetime.timedelta(minutes=30))
  
  
  def calculate_distance(lat1, lon1, lat2, lon2):
      wgs84 = nvector.FrameE(name='WGS84')
      point1 = wgs84.GeoPoint(latitude=lat1, longitude=lon1, degrees=True)
      point2 = wgs84.GeoPoint(latitude=lat2, longitude=lon2, degrees=True)
      s_12, _azi1, _azi2 = point1.distance_and_azimuth(point2)
  
      return s_12 / 1000 / 1.852  # nm
  
  
  def convert_time(nt):
      decimal_part = nt % 1
      minutes = int(decimal_part * 60)
      hours = int(nt)
  
      return f&quot;{hours}h {minutes}m&quot;
  
  
  if __name__ == &quot;__main__&quot;:
      main()
  </code></pre>
  <p>When it does have night time, it throws the error:</p>
  <p>e.g.: <code>python ./night_time.py LKPR1720LKMT181020200401</code></p>
  <p>but not for <code>python ./night_time.py LKPR1220LKMT131020200401</code></p>