Reputation: 25
I'm making a giveaway command for my Discord bot, I want to convert seconds into days, months + hours Here's my code:
try:
duration = time.split('d')[0] * 86400
except IndexError:
try:
duration = time.split('h')[0] * 3600
except IndexError:
try:
duration = time.split('m')[0] * 60
except IndexError:
pass
print(duration)
Ignore the indentations, they're normal in VS Code. 'time' is defined as '1m' which then I split the 'm' which results to '1' It prints duration like '1m' atleast like a bunch of times. I enter a duration defined as 'time' for example '2d' which I want to result that in seconds which would be 172800 seconds.
Upvotes: 0
Views: 357
Reputation: 40894
It does not work because str.split
returns the whole string is there's no split character:
>>> print('aaa'.split('b'))
['aaa']
>>> _
I would do it in a shorter and more explicit way.
import re
SECONDS_IN = { # Number of seconds per suffix.
'm': 60, # minute.
'h': 3600, # hour.
'd': 86400, # day.
}
def time_in_sec(s):
# Split by either m, d, or h.
pieces = re.split('(m|d|h)', s)
if len(pieces) < 2: # Did not split.
raise ValueError('%r is not a valid time string' % s)
amount = pieces[0] # The number.
suffix = pieces[1] # The m, d, or h.
return int(amount) * SECONDS_IN[suffix]
Now you can try:
for s in ['5m', '2h', '1d', '100k']:
print(s, '=', time_in_sec(s), 'seconds')
5m = 300 seconds
2h = 7200 seconds
1d = 86400 seconds
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in time_in_sec
ValueError: '100k' is not a valid time string
This of course is still very far from a robust parser.
If you want to handle input in a robust way, consider a library like arrow
.
Upvotes: 1