Page 1 of 1

[Cs:s] Ban Counter

Posted: Fri Feb 12, 2021 4:47 pm
by cssbestrpg
Hi, i have small issue with my ban counter code. I want to show weeks/days/hours/minutes.
This code suppose to count remaining ban, but i can't solve count correctly.
For example if you ban for 4weeks and some times goes, it shows 3.94 Week(s) as remaing timeleft.
But i want it shows weeks and days of remaining time instead 3.94

Syntax: Select all

def ban_counter(timeleft):
if timeleft < 0:
return '0 Seconds'
elif timeleft < 60:
stime = '%.2f' % (timeleft)
return '%s Second(s)' % (stime)
elif timeleft < 3600:
minute = timeleft / 60
mins = '%.2f' % (minute)
return '%s Minute(s)' % (mins)
elif timeleft < 86400:
hours = timeleft / 60 / 60
d_hours = '%.2f' % (hours)
return '%s Hour(s)' % (d_hours)
elif timeleft < 604800:
days = timeleft / 60 / 24 / 60
s_day = '%.2f' % (days)
return '%s Day(s)' % (s_day)
elif timeleft < 2419200:
week = timeleft / 60 / 24 / 60 / 7
weeks = '%.2f' % (week)
return '%s Week(s)' % (weeks)
else:
return '%s Second(s)' % (timeleft)

Re: [Cs:s] Ban Counter

Posted: Fri Feb 12, 2021 6:39 pm
by Ayuto
You need to take every unit into account. E. g. something like this:

Syntax: Select all

# A tuple that stores the seconds to unit conversion factor.
UNITS = (
# You can enable/disable a unit by simply commenting it out
# or remove the comment.
#('month', 'months', 1 * 60 * 60 * 24 * 30),
('week', 'weeks', 1 * 60 * 60 * 24 * 7),
('day', 'days', 1 * 60 * 60 * 24),
('hour', 'hours', 1 * 60 * 60),
('minute', 'minutes', 1 * 60),
('second', 'seconds', 1)
)

def seconds_to_units(seconds, units=UNITS):
result = []
for singular, plural, factor in units:
value, seconds = divmod(seconds, factor)
if not value:
continue

if value == 1:
result.append(f'{value} {singular}')
else:
result.append(f'{value} {plural}')

return ' '.join(result)

print(seconds_to_units(120000))

Code: Select all

1 day 9 hours 20 minutes
This is basically just an adoption of this:
https://stackoverflow.com/a/24542445

The code above is just a little bit faster and easier to influence and translatable.

Re: [Cs:s] Ban Counter

Posted: Fri Feb 12, 2021 7:31 pm
by satoon101
If you don't absolutely need weeks to be a factor, I would suggest not reinventing the wheel and just use datetime.timedelta, which is also demonstrated in the link Ayuto provided. Or, at the very least, you could convert the weeks first and then use timedelta on the remaining seconds.

Re: [Cs:s] Ban Counter

Posted: Sat Feb 13, 2021 2:06 pm
by cssbestrpg
Hi thanks for answer i got it work