Compare current time with file values

Asked

Viewed 97 times

1

I’m trying to get a list of schedules of a file (I already got), and schedule according to the time: purchase scheduled for 15:30, at this time I will run the purchase (API.Buy)

# alimentação
sinal vem do arquivo TXT
lista = (23,5,2020,18:10,EURJPY-OTC,PUT) 
today = datetime.today()

for sinal in lista:
    dados = sinal.split(',')

    # Divide variáveis
    dados[3] = datetime.strptime(dados[3], '%H:%M').time()

    #compara horários
    if(dados[3]==today): 
        API.buy(entrada,dados[4],dados[5],5)
        #valor, moeda, direção, tempo;
      
print("Operação efetuada...")

1 answer

2

The time comparison you are doing will not work.

When you do the Parsing of a string that only has the hour and the minute ('%H:%M'), seconds and fractions of a second are set to zero. In addition, the method time() returns a datetime.time, i.e., an object that contains only time fields, regardless of the day. Ex:

print(datetime.strptime('18:30', '%H:%M').time()) # 18:30:00

But when you use datetime.today, the time contains the current time, including seconds and fractions of a second:

print(datetime.today()) # 2020-07-27 09:28:57.649383

Moreover, today also returns the date (day, month and year). That is, even if the hours and minutes are equal, the other fields will not be.

Therefore, for the comparison to work, we need to extract only the time fields of today and set the seconds and fractions of a second to zero, using replace:

# pega somente o horário com time(), e seta os segundos e frações de segundo para zero com replace()
today = datetime.today().time().replace(second=0, microsecond=0)

for sinal in lista:
    dados = sinal.split(',')
    dados[3] = datetime.strptime(dados[3], '%H:%M').time()
    # compara horários
    if(dados[3] == today):
        # etc...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.