Python에서 즉각에서 얻는 값과 변수를 빼서 120이라는 고정값이랑 비교하려면?

조회수 777회
if sheet["A" + str(i)].value == a1.name:
rn = random.randint(1,100)
percent = sheet["B" + str(i)].value
level = sheet["C" + str(i)].value
cooltime = sheet["D" + str(i)].value
if datetime.datetime.now()- cooltime >= 120:  # <- 여기가 라인 52입니다.

에러가 invalid syntax (, line 52)pylint(syntax-error) 이렇게 나왔습니다. 해결해주실 수 있나요??? 이 에러 때문에 몇 일이나 봇 개발을 못하고 있습니다. 참고로 임포트는 다 했습니다. 모듈 설치도 다 했습니다.

정보 추가:

import discord
from discord.ext import commands
import openpyxl
import random
import datetime
import os

bot = commands.Bot(command_prefix = '/')
global filename
filename = '강화.xlsx'

@bot.event
async def on_ready():
    print('강화봇이 작동되었습니다.')

#메세지를 받을 수 있게 옵션처리
@bot.command(pass_context=True)
async def 강화(ctx):
    a1 = ctx.message.author

    # 파일위치를 실행파일의 위치와 동일하게 하기 위해 실행파일 위치를 확인한다
    BASE_PATH = os.path.dirname(os.path.abspath(__file__))+"\\"
    # 파일이 없을 경우 최초 생성
    if os.path.isfile(BASE_PATH+filename) == False:
        newbook = openpyxl.Workbook()
        newbook.save(BASE_PATH+filename)
        newbook.close()
        newbook = None
        #파일을 만들었다는걸 프린트함
        print("강화파일 만듬")

    print ("파일위치:"+os.path.abspath(BASE_PATH+filename))

    book = openpyxl.load_workbook(BASE_PATH+filename)
    sheet = book.worksheets[0]
    i = 1
    # 엑셀을 계속 찾을지 확인하기 위한 변수
    needLoop = True
    while needLoop:
        print ("Row No."+str(i)+" 확인중...")
        print ("사용자번호 : "+str(a1))
        print ("엑셀 사용자번호 : %s"%sheet["A" + str(i)].value)
        print ("엑셀 확률 : %s"%sheet["B" + str(i)].value)
        print ("엑셀 레벨 : %s"%sheet["C" + str(i)].value)
        print ("엑셀 마지막시간 : %s"%sheet["D" + str(i)].value)
        if sheet["A" + str(i)].value == a1.name:
            rn = random.randint(1,100)
            percent = sheet["B" + str(i)].value
            level = sheet["C" + str(i)].value
            cooltime = sheet["D" + str(i)].value
            dt = datetime.datetime.now()
            if dt - cooltime >= 120:
                if rn >= percent:
                    level = sheet["C" + str(i)].value + 1
                    percent = sheet["B" + str(i)].value / 3
                    sheet["C" + str(i)] = level
                    sheet["B" + str(i)] = percent
                    cooltime = datetime.datetime.now()
                    sheet["D" + str(i)].value = cooltime
                    book.save(filename)
                    ctx.send(a1+"님이"+str(level)+"레벨로 올렸습니다. 강화후 확률:"+str(percent))
                else:
                    level = sheet["C" + str(i)].value - 1
                    percent = sheet["B" + str(i)].value * 3
                    sheet["C" + str(i)] = level
                    sheet["B" + str(i)] = percent
                    cooltime = datetime.datetime.now()
                    sheet["D" + str(i)].value = cooltime
                    book.save(filename)
                    ctx.send(a1+"님이"+str(level)+"레벨로 내려갔습니다. 강화후 확률:"+str(percent))
            else:
                ctx.send(a1+"님"+str(cooltime)+"만큼 쿨타임이 남았습니다.")
        elif (sheet["A" + str(i)].value == None):
            #엑셀에 정보가 없으면 끝내면서 현재 사용자 초기치 넣기
            sheet["A" + str(i)] = a1.name
            sheet["B" + str(i)] = 100
            sheet["C" + str(i)] = 1
            sheet["D" + str(i)] = datetime.datetime.now()
            i = i + 1
            print("유저 데이터 생성 완료")
    needLoop = False
    i = i + 1
    print ("강화 실행 끝")
    book.save(BASE_PATH+filename)
    # 저장이 가능한 시점에서는 while을 벗어난다.
    book.close()
    ctx.send('유저 데이터를 생성했습니다. 다시 /강화를 쳐주세요.')

bot.run('bot_token') # <- 실제로는 디스코드 봇 토큰입니다. 봇 토큰이 유출되면 안되기 때문에 이렇게 비공개 해놨습니다. 무시해주세요.
  • (•́ ✖ •̀)
    알 수 없는 사용자
  • 에러메시지는 문법 에러이고 (, 부분이 문제라는데 코드에는 없습니다. 오류 재현이 되는 코드를 올려보시기 바랍니다. 정영훈 2019.12.24 19:24
  • 3자가 동작시켜서 에러가 재현되는 코드를 올려달라는 이야깁니다...그래야 트러블 슈팅을 하겠지요...런타임 오류라 해볼 수 없다면 추측밖엔 못합니다. 정영훈 2019.12.25 20:04

2 답변

  • datetime.datetime.now()는 반환형이 datetime.datetime 입니다.

    1. 만일 cooltime의 형이 datetime.datetime 이라면, - 연산이 가능 하지만 이 연산의 결과는 datetime.timedelta 이므로 숫자형인 120과 비교 연산이 불가 할 것 입니다.
    2. 만일 cooltime의 형이 숫자이거나, 문자라면 - 연산 부터 수행이 되지 않을 것 입니다.
    • (•́ ✖ •̀)
      알 수 없는 사용자
    • syntax 오류이니 타입에 따른 문제같지는 않아보이는군요. 정영훈 2019.12.24 19:26
    • syntax 오류라면 타입 문제 같지는 않을 것 같군요. 그런데, 코드를 보면 cooltime이 sheet['D'+숫자] 에 들어 있는 값인데, 초기치 넣는 곳을 보면 datetime.datetime 형을 넣고 있어서, 결국 datetime.timedelta 와 숫자를 비교하고 있어서 이부분도 문제는 문제 같습니다. 알 수 없는 사용자 2019.12.26 14:06
  • 엑셀의 값을 가져오는 cooltime 변수 value 값을 확인해보실 것을 권장드립니다.
    질문에 올려주신 코드가 전체코드라면
    해당 value에서 괄호가 포함된 string타입의 데이터가 들어와서 생기는 문제라고 판단할 수 밖에없네요.

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)