How to set a date restriction for returned events in Google Calendar and put them in order - Python
Question: Ok, so I've seen similar questions to this, but most of them are in regards to
different languages, none seem to be within the realm of Python. I've also
searched the documentation on Google for the different options with listing
events in a Calendar. There is no method listed by Google to restrict the
results by order of state date, only start time.

So, I was hoping someone could help me with a way to retrieve events from a
calendar get them in order, and at the same time, restrict the results to a
specific date. Preferably I'd like to not get any events farther than 30 days
out and order them by start time and date. My guess, while I'm not sure of the
best way to do it, would be to get all the events, put them in a list or
dictionary maybe, then maybe enumerate that list or dictionary into the order
I want and then do some if statements to remove anything from the list or
dictionary that's farther than 30 days out. Below is the code I'm using and
then the response I get in the terminal. As you can see I get dates that are a
year out and they're all out of order. Oh and just so you aren't confused,
this code is pulling from multiple parts of my overall calendar in Google.
Additionally, you'll notice I limited the results to a maximum of 5 to make
testing easier so I wasn't returning 100's of results.

    
    
    try:
      #  -----  Facebook Birthday Calendar  -----
      page_token = None
      interval = 0
      while True:
        events = service.events().list(calendarId='my calendar id', pageToken=page_token).execute()
        for event in events['items']:
          if interval < 5:
        dt = dateutil.parser.parse(event['start']['date'])
        print event['summary'], dt.strftime('%d %m %Y')
        page_token = events.get('nextPageToken')
        interval += 1
      else:
        break
        if not page_token:
      break
    print "-----"
    
    #  -----  My Gmail Calendar  -----
    page_token_two = None
    interval_two = 0
    while True:
      events_two = service.events().list(calendarId='my calendar id', pageToken=page_token_two).execute()
      for event_two in events_two['items']:
        if interval_two < 5:
      dt_two = dateutil.parser.parse(event_two['start']['dateTime'])
      dstime_two = dateutil.parser.parse(event_two['start']['dateTime'])
      detime_two = dateutil.parser.parse(event_two['end']['dateTime'])
          print event_two['summary'] + " " + dt_two.strftime('%d %m %Y') + " " + dstime_two.strftime('%H%M') + "-" + detime_two.strftime('%H%M')
          # print event_two['summary'], dt_two.strftime('%d %m %Y')
      page_token_two = events_two.get('nextPageToken')
      interval_two += 1
    else:
      break
      if not page_token_two:
    break
    print "-----"
    
    #  -----  US Holidays Calendar  -----
    page_token_three = None
    interval_three = 0
    while True:
      events_three = service.events().list(calendarId='my calendar id', pageToken=page_token_three).execute()
      for event_three in events_three['items']:
        if interval_three < 5:
      dt_three = dateutil.parser.parse(event_three['start']['date'])
      print event_three['summary'], dt_three.strftime('%d %m %Y')
      page_token_three = events_three.get('nextPageToken')
      interval_three += 1
    else:
      break
      if not page_token_three:
    break
    print "-----"
    

Results:

    
    
    Person's Birthday 17 03 2014
    Person's Birthday 20 09 2013
    Person's Birthday 10 09 2013
    Person's Birthday 17 04 2014
    Person's Birthday 29 04 2014
    -----
    Work 12 04 2013 1430-2330
    Work 15 04 2013 1415-2315
    Work 22 04 2013 1415-2315
    Work 25 04 2013 1405-2305
    Work 29 04 2013 0640-0230
    -----
    Patriot Day 11 09 2012
    Thanksgiving 28 11 2013
    Groundhog Day 02 02 2014
    Memorial Day 28 05 2012
    Lincoln's Birthday 12 02 2013
    -----
    


Answer: Python datetime objects are very easy to work with. For instance, you could
collect your event and datetime information into a list of tuples, like this:

    
    
    all_events = []
    for <loop over events from server>:
        all_events.append((dateutil.parser.parse(event['start']['date']), event['summary']))
    

And then you can filter and sort those tuples, using the fact that you can
add/subtract datetimes and get timedelta objects. You can simply compare to a
timedelta object which represents a difference of 30 days:

    
    
    from datetime import datetime, timedelta
    
    max_td = timedelta(days=30)
    now = datetime.now()
    
    # Remove events that are too far into the future
    filtered_events = filter(lambda e: e[0] - now <= max_td, all_events)
    
    # Sort events in ascending order of start time
    filtered_events.sort()
    

