2

I'm new to python and coding in general, I have developed a small program that checks for double booking in google calendar. My problem is if I chose to check the 26 June, it will check for the 26 AND for the 27.

I think it's because I did a for i in range(1) (So it loops twice, (0,1))

How do i change it to make it run only once ?

here is the code :

        for i in range(1):

            startStrip = datetime.datetime.strptime(event_start, "%Y-%m-%dT%H:%M:%S")
            endStrip = datetime.datetime.strptime(event_end, "%Y-%m-%dT%H:%M:%S")
            dayOfWeek = startStrip + datetime.timedelta(days=i)
            # les bons formats
            currentStart = str(startStrip + datetime.timedelta(days=i)).replace(" ", "T")
            currentEnd = str(endStrip + datetime.timedelta(days=i)).replace(" ", "T")
            calendarEnd = str(endStrip + datetime.timedelta(days=i + 1)).replace(" ", "T")

            events_result = service.events().list(calendarId='primary', timeMin=currentStart + "-00:00",
                                                  maxResults=30, timeMax=calendarEnd + "-00:00",
                                                  singleEvents=True, orderBy='startTime').execute()
            events = events_result.get('items', [])

            currentEmployees = []
            for event in events:
                currentEmployees.append(event['summary'])

            #for i in range(1):
            #event_done = False
            if employee in currentEmployees:
                event_done = False
                event['summary'] = employee
                #if employee not in currentEmployees:
                    #event_done = True
                #else:
                for event in events:
                   # if employee == event['summary']:
                   if str2datetime(currentStart) <= str2datetime(event['end']['dateTime'].split('+')[0]) and str2datetime(currentEnd) >= str2datetime(event['start']['dateTime'].split('+')[0]):
                    event_done = False
                    print(employee + ' est occupé')
                    break
                   else:
                      event_done = True
                      break

            if employee not in currentEmployees:
                event_done = True

            if event_done:
                option = show_message_box(QMessageBox.Critical,
                                      "Confirmation",
                                      "Voulez-vous bloquer cette plage horraire?"\
                                      "L'employé : \"" + employee + "\" sera marqué comme indisponible en raison de : " + reason, \
                                      "Nom de l'employé: " + employee + "\n" \
                                      "Raison: " + reason + "\n" \
                                      "À partir du : " + currentStart + "\n" \
                                      "À ce jour " + currentEnd + "\n"
                                      )

                if option == QMessageBox.Yes:
                    event_done = True
                else:
                    print("Événement ignoré!")
                    event_done = False
                    break

                if event_done:
                    event = {
                        'summary': employee,
                        'location': location,
                        'description': reason,
                        'start': {
                            'dateTime': currentStart,
                            'timeZone': 'America/New_York',
                        },
                        'end': {
                            'dateTime': currentEnd,
                            'timeZone': 'America/New_York',
                        #},
                        #'attendees': [
                         #   {'email': event_email},
                        #],
                        #'reminders': {
                         #   'useDefault': True,
                        },
                    }
                    register_event(service, event)

            else:
                second_message_box(QMessageBox.Critical,
                                      "ATTENTION!",
                                      "L'inspecteur " + employee + " est déjà occupé à ce moment-là.""\n" \
                                      "Veuillez essayer une autre plage horraire.", QMessageBox.Ok)
6
  • 2
    Get rid of the loop? Loops are for when you need to execute that part of the code multiple times. Commented Jun 24, 2020 at 23:26
  • 2
    Also, for i in range(1): will only have one iteration (i.e., 0). Commented Jun 24, 2020 at 23:29
  • Could you try and simplify your code into a minimal reproducible example? Commented Jun 24, 2020 at 23:30
  • I can't. And even I could, i wouldn't know how. My GUI opens, i select start date and end date, and run the code, this function gets called and it format the dates to fit the google standard, check in the chosen day if the employee selected is busy at selected hours, if not, will add events, if not will give me error message. MY problem is it checks for the following day also. I wouldn'T know how to reproduce an example, i'm sorry. @DanielWalker Commented Jun 25, 2020 at 0:03
  • so if you look at my code, it runs only once? I thought range(1) returns [0,1], which just makes that loop twice @DanielWalker Commented Jun 25, 2020 at 0:04

2 Answers 2

2

Your first loop is fine , it will iterate only once I don't know your requirement logic but what I can see is your calander_end you are making it with +1 which is besically taking one date ahead I guess you have to check and rectify according to your requirement

Sign up to request clarification or add additional context in comments.

1 Comment

I just realized in 1 second before you sent your answer.!!! thank you!
0

Firstly, the range() function calls values up to the 'stop' input, meaning you don't get 0 and 1, you only get 0 for i, secondly, if you are only going to go through the code once, you don't need the loop at all? If you don't want to erase it though, you can put a 'break' at the end of the loop block, which would cut the loop from running again

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.