Summing up datetimes without using pandas












2















I have a data set of rain fall in half hour intervals. I want to sum up the rainfall for each day and keep track of how many data points are summed per day to account for data gaps. Then I want to create a new file with a column for the date, a column for the rainfall, and a column for how many data points were available to sum for each day.
daily sum is my function that is trying to do this, get data is my function for extracting the data.



def get_data(avrains):
print('opening{}'.format(avrains))
with open(avrains, 'r') as rfile:
header = rfile.readline()
dates =
rainfalls =
for line in rfile:
line = (line.strip())
row = line.split(',')
d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
r = row[-1]
dates.append(d)
rainfalls.append(float(r))
data = zip(dates, rainfalls)
data = sorted(data)
return (data)

def dailysum(rains):
day_date =
rain_sum =
for i in rains:
dayi = i[0]
rainsi = i[1]
for i in dayi:
try:
if dayi[i]== dayi[i+1]:
s= rains[i]+rains[i+1]
rain_sum.append(float(s))
except:
pass
day_date.append(dayi[i])









share|improve this question





























    2















    I have a data set of rain fall in half hour intervals. I want to sum up the rainfall for each day and keep track of how many data points are summed per day to account for data gaps. Then I want to create a new file with a column for the date, a column for the rainfall, and a column for how many data points were available to sum for each day.
    daily sum is my function that is trying to do this, get data is my function for extracting the data.



    def get_data(avrains):
    print('opening{}'.format(avrains))
    with open(avrains, 'r') as rfile:
    header = rfile.readline()
    dates =
    rainfalls =
    for line in rfile:
    line = (line.strip())
    row = line.split(',')
    d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
    r = row[-1]
    dates.append(d)
    rainfalls.append(float(r))
    data = zip(dates, rainfalls)
    data = sorted(data)
    return (data)

    def dailysum(rains):
    day_date =
    rain_sum =
    for i in rains:
    dayi = i[0]
    rainsi = i[1]
    for i in dayi:
    try:
    if dayi[i]== dayi[i+1]:
    s= rains[i]+rains[i+1]
    rain_sum.append(float(s))
    except:
    pass
    day_date.append(dayi[i])









    share|improve this question



























      2












      2








      2








      I have a data set of rain fall in half hour intervals. I want to sum up the rainfall for each day and keep track of how many data points are summed per day to account for data gaps. Then I want to create a new file with a column for the date, a column for the rainfall, and a column for how many data points were available to sum for each day.
      daily sum is my function that is trying to do this, get data is my function for extracting the data.



      def get_data(avrains):
      print('opening{}'.format(avrains))
      with open(avrains, 'r') as rfile:
      header = rfile.readline()
      dates =
      rainfalls =
      for line in rfile:
      line = (line.strip())
      row = line.split(',')
      d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
      r = row[-1]
      dates.append(d)
      rainfalls.append(float(r))
      data = zip(dates, rainfalls)
      data = sorted(data)
      return (data)

      def dailysum(rains):
      day_date =
      rain_sum =
      for i in rains:
      dayi = i[0]
      rainsi = i[1]
      for i in dayi:
      try:
      if dayi[i]== dayi[i+1]:
      s= rains[i]+rains[i+1]
      rain_sum.append(float(s))
      except:
      pass
      day_date.append(dayi[i])









      share|improve this question
















      I have a data set of rain fall in half hour intervals. I want to sum up the rainfall for each day and keep track of how many data points are summed per day to account for data gaps. Then I want to create a new file with a column for the date, a column for the rainfall, and a column for how many data points were available to sum for each day.
      daily sum is my function that is trying to do this, get data is my function for extracting the data.



      def get_data(avrains):
      print('opening{}'.format(avrains))
      with open(avrains, 'r') as rfile:
      header = rfile.readline()
      dates =
      rainfalls =
      for line in rfile:
      line = (line.strip())
      row = line.split(',')
      d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
      r = row[-1]
      dates.append(d)
      rainfalls.append(float(r))
      data = zip(dates, rainfalls)
      data = sorted(data)
      return (data)

      def dailysum(rains):
      day_date =
      rain_sum =
      for i in rains:
      dayi = i[0]
      rainsi = i[1]
      for i in dayi:
      try:
      if dayi[i]== dayi[i+1]:
      s= rains[i]+rains[i+1]
      rain_sum.append(float(s))
      except:
      pass
      day_date.append(dayi[i])






      python datetime






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 20:46









      Tim

      1,759620




      1,759620










      asked Nov 14 '18 at 20:40









      Sarah ReuterSarah Reuter

      111




      111
























          1 Answer
          1






          active

          oldest

          votes


















          0














          There's a lot of ways to solve this, but I'll try to stay as close to your existing code as I can:



          def get_data(avrains):
          """
          opens the file specified in avrains and returns a dictionary
          keyed by date, containing a 2-tuple of the total rainfall and
          the count of data points, like so:
          {
          date(2018, 11, 1) : (0.25, 6),
          date(2018, 11, 2) : (0.00, 5),
          }
          """
          print('opening{}'.format(avrains))
          rainfall_totals = dict()

          with open(avrains, 'r') as rfile:
          header = rfile.readline()
          for line in rfile:
          line = (line.strip())
          row = line.split(',')
          d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
          r = row[-1]

          try:
          daily_rainfall, daily_count = rainfalls[d]
          daily_rainfall += r
          daily_count += 1
          rainfalls[d] = (daily_rainfall, daily_count)
          except KeyError:
          # if we don't find that date in rainfalls, add it
          rainfalls[d] = (r, 1)

          return rainfalls


          Now when you call get_data("/path/to/file"), you'll get back a dictionary. You can spit out the values with some thing like this:



          foo = get_data("/path/to/file")
          for (measure_date, (rainfall, observations)) in foo.items():
          print measure_date, rainfall, observations


          (I will leave the formatting of the date, and any sorting or file-writing as an exercise :) )






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308405%2fsumming-up-datetimes-without-using-pandas%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            There's a lot of ways to solve this, but I'll try to stay as close to your existing code as I can:



            def get_data(avrains):
            """
            opens the file specified in avrains and returns a dictionary
            keyed by date, containing a 2-tuple of the total rainfall and
            the count of data points, like so:
            {
            date(2018, 11, 1) : (0.25, 6),
            date(2018, 11, 2) : (0.00, 5),
            }
            """
            print('opening{}'.format(avrains))
            rainfall_totals = dict()

            with open(avrains, 'r') as rfile:
            header = rfile.readline()
            for line in rfile:
            line = (line.strip())
            row = line.split(',')
            d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
            r = row[-1]

            try:
            daily_rainfall, daily_count = rainfalls[d]
            daily_rainfall += r
            daily_count += 1
            rainfalls[d] = (daily_rainfall, daily_count)
            except KeyError:
            # if we don't find that date in rainfalls, add it
            rainfalls[d] = (r, 1)

            return rainfalls


            Now when you call get_data("/path/to/file"), you'll get back a dictionary. You can spit out the values with some thing like this:



            foo = get_data("/path/to/file")
            for (measure_date, (rainfall, observations)) in foo.items():
            print measure_date, rainfall, observations


            (I will leave the formatting of the date, and any sorting or file-writing as an exercise :) )






            share|improve this answer




























              0














              There's a lot of ways to solve this, but I'll try to stay as close to your existing code as I can:



              def get_data(avrains):
              """
              opens the file specified in avrains and returns a dictionary
              keyed by date, containing a 2-tuple of the total rainfall and
              the count of data points, like so:
              {
              date(2018, 11, 1) : (0.25, 6),
              date(2018, 11, 2) : (0.00, 5),
              }
              """
              print('opening{}'.format(avrains))
              rainfall_totals = dict()

              with open(avrains, 'r') as rfile:
              header = rfile.readline()
              for line in rfile:
              line = (line.strip())
              row = line.split(',')
              d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
              r = row[-1]

              try:
              daily_rainfall, daily_count = rainfalls[d]
              daily_rainfall += r
              daily_count += 1
              rainfalls[d] = (daily_rainfall, daily_count)
              except KeyError:
              # if we don't find that date in rainfalls, add it
              rainfalls[d] = (r, 1)

              return rainfalls


              Now when you call get_data("/path/to/file"), you'll get back a dictionary. You can spit out the values with some thing like this:



              foo = get_data("/path/to/file")
              for (measure_date, (rainfall, observations)) in foo.items():
              print measure_date, rainfall, observations


              (I will leave the formatting of the date, and any sorting or file-writing as an exercise :) )






              share|improve this answer


























                0












                0








                0







                There's a lot of ways to solve this, but I'll try to stay as close to your existing code as I can:



                def get_data(avrains):
                """
                opens the file specified in avrains and returns a dictionary
                keyed by date, containing a 2-tuple of the total rainfall and
                the count of data points, like so:
                {
                date(2018, 11, 1) : (0.25, 6),
                date(2018, 11, 2) : (0.00, 5),
                }
                """
                print('opening{}'.format(avrains))
                rainfall_totals = dict()

                with open(avrains, 'r') as rfile:
                header = rfile.readline()
                for line in rfile:
                line = (line.strip())
                row = line.split(',')
                d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
                r = row[-1]

                try:
                daily_rainfall, daily_count = rainfalls[d]
                daily_rainfall += r
                daily_count += 1
                rainfalls[d] = (daily_rainfall, daily_count)
                except KeyError:
                # if we don't find that date in rainfalls, add it
                rainfalls[d] = (r, 1)

                return rainfalls


                Now when you call get_data("/path/to/file"), you'll get back a dictionary. You can spit out the values with some thing like this:



                foo = get_data("/path/to/file")
                for (measure_date, (rainfall, observations)) in foo.items():
                print measure_date, rainfall, observations


                (I will leave the formatting of the date, and any sorting or file-writing as an exercise :) )






                share|improve this answer













                There's a lot of ways to solve this, but I'll try to stay as close to your existing code as I can:



                def get_data(avrains):
                """
                opens the file specified in avrains and returns a dictionary
                keyed by date, containing a 2-tuple of the total rainfall and
                the count of data points, like so:
                {
                date(2018, 11, 1) : (0.25, 6),
                date(2018, 11, 2) : (0.00, 5),
                }
                """
                print('opening{}'.format(avrains))
                rainfall_totals = dict()

                with open(avrains, 'r') as rfile:
                header = rfile.readline()
                for line in rfile:
                line = (line.strip())
                row = line.split(',')
                d = datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
                r = row[-1]

                try:
                daily_rainfall, daily_count = rainfalls[d]
                daily_rainfall += r
                daily_count += 1
                rainfalls[d] = (daily_rainfall, daily_count)
                except KeyError:
                # if we don't find that date in rainfalls, add it
                rainfalls[d] = (r, 1)

                return rainfalls


                Now when you call get_data("/path/to/file"), you'll get back a dictionary. You can spit out the values with some thing like this:



                foo = get_data("/path/to/file")
                for (measure_date, (rainfall, observations)) in foo.items():
                print measure_date, rainfall, observations


                (I will leave the formatting of the date, and any sorting or file-writing as an exercise :) )







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 15 '18 at 0:44









                Chris CurveyChris Curvey

                3,00442742




                3,00442742






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308405%2fsumming-up-datetimes-without-using-pandas%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Xamarin.form Move up view when keyboard appear

                    JBPM : POST request for execute process go wrong