简体   繁体   中英

Python | Issue with turning seconds into days, months, hours

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM