Reputation: 11
I'm trying to make a python bot and as one off the commands i want to dsiplay how long it will be until the server restarts (11pm est) every day.
this is the code i wrote but it gives some weird outputs sometimes, when it's midnight it returns 40 hours until restart.
Can anyone help me out here?
@client.command()
async def gettime(self):
now = datetime.now()
# 11 est == 17 gmt+1
reset = datetime.strptime('16:00', '%H:%M')
if now == reset:
await self.send('the restart is happening now')
elif now < reset:
untilrestarthour = reset.hour - now.hour
untilrestartminute = 60 - now.minute
await self.send(f'the restart is happening in {untilrestarthour} hours and {untilrestartminute}''s ')
elif now > reset:
untilrestarthour = 24 - (now.hour - reset.hour)
untilrestartminute = 60 - now.minute
await self.send(f'the restart is happening in {untilrestarthour} hours and {untilrestartminute} minute''s ')
else:
await self.send("error")
Upvotes: 1
Views: 1388
Reputation: 142641
In current version you substract from 24h and from 60minutes so finally you substract from 24h+60minutes
which gives 25h
. You would have to do something like
untilrestarthour = reset.hour - now.hour
if now.minute > 0:
untilrestarthour -= 1
untilrestartminute = 60 - now.minute
else:
untilrestartminute = 0
But maybe better you should use correct date instead of 1900-01-01
and then you can use now - reset
or reset - now
to calculate hours and minutes correctly.
from datetime import datetime, timedelta
now = datetime.now()
reset = now.replace(hour=16, minute=0)
#reset += timedelta(days=1) # next day
print(' now:', now)
print('reset:', reset)
print('reset-now:', reset-now)
print('now-reset:', now-reset)
if now == reset:
print('the restart is happening now')
elif now < reset:
print('reset in the future:', reset-now)
elif now > reset:
print('reset in the past:', now-reset)
else:
print("error")
Result
now: 2020-05-20 17:49:04.029570
reset: 2020-05-20 16:00:04.029570
reset-now: -1 day, 22:11:00
now-reset: 1:49:00
reset in the past: 1:49:00
The only problem is that now - reset
(reset - now
) creates object datetime.timedelta
which can generate string 1:49:00
but it can't gives separatelly hours 1 and minutes 49. It gives only total seconds and you have to manually conver seconds to hours and minutes
print('reset:', reset)
print(' now:', now)
diff = (reset-now)
print('diff:', diff)
seconds = diff.seconds
print('seconds:', seconds)
hours = seconds//3600
seconds = seconds % 3600
minutes = seconds // 60
seconds = seconds % 60
print('hours:', hours, '| minutes:', minutes, '| seconds:', seconds)
Result:
reset: 2020-05-21 16:00:37.395018
now: 2020-05-20 18:00:37.395018
diff: 22:00:00
seconds: 79200
hours: 22 | minutes: 0 | seconds: 0
Upvotes: 1