Python function to convert seconds into minutes, hours, and days

前端 未结 16 1394
不思量自难忘°
不思量自难忘° 2020-11-28 07:27

Question: Write a program that asks the user to enter a number of seconds, and works as follows:

  • There are 60 seconds in a minute. If the number of seconds

16条回答
  •  爱一瞬间的悲伤
    2020-11-28 08:14

    These functions are fairly compact and only use standard Python 2.6 and later.

    def ddhhmmss(seconds):
        """Convert seconds to a time string "[[[DD:]HH:]MM:]SS".
        """
        dhms = ''
        for scale in 86400, 3600, 60:
            result, seconds = divmod(seconds, scale)
            if dhms != '' or result > 0:
                dhms += '{0:02d}:'.format(result)
        dhms += '{0:02d}'.format(seconds)
        return dhms
    
    
    def seconds(dhms):
        """Convert a time string "[[[DD:]HH:]MM:]SS" to seconds.
        """
        components = [int(i) for i in dhms.split(':')]
        pad = 4 - len(components)
        if pad < 0:
            raise ValueError('Too many components to match [[[DD:]HH:]MM:]SS')
        components = [0] * pad + components
        return sum(i * j for i, j in zip((86400, 3600, 60, 1), components))
    

    And here are tests to go with them. I'm using the pytest package as a simple way to test exceptions.

    import ddhhmmss
    
    import pytest
    
    
    def test_ddhhmmss():
        assert ddhhmmss.ddhhmmss(0) == '00'
        assert ddhhmmss.ddhhmmss(2) == '02'
        assert ddhhmmss.ddhhmmss(12 * 60) == '12:00'
        assert ddhhmmss.ddhhmmss(3600) == '01:00:00'
        assert ddhhmmss.ddhhmmss(10 * 86400) == '10:00:00:00'
        assert ddhhmmss.ddhhmmss(86400 + 5 * 3600 + 30 * 60 + 1) == '01:05:30:01'
        assert ddhhmmss.ddhhmmss(365 * 86400) == '365:00:00:00'
    
    
    def test_seconds():
        assert ddhhmmss.seconds('00') == 0
        assert ddhhmmss.seconds('02') == 2
        assert ddhhmmss.seconds('12:00') == 12 * 60
        assert ddhhmmss.seconds('01:00:00') == 3600
        assert ddhhmmss.seconds('1:0:0') == 3600
        assert ddhhmmss.seconds('3600') == 3600
        assert ddhhmmss.seconds('60:0') == 3600
        assert ddhhmmss.seconds('10:00:00:00') == 10 * 86400
        assert ddhhmmss.seconds('1:05:30:01') == 86400 + 5 * 3600 + 30 * 60 + 1
        assert ddhhmmss.seconds('365:00:00:00') == 365 * 86400
    
    
    def test_seconds_raises():
        with pytest.raises(ValueError):
            ddhhmmss.seconds('')
        with pytest.raises(ValueError):
            ddhhmmss.seconds('foo')
        with pytest.raises(ValueError):
            ddhhmmss.seconds('1:00:00:00:00')
    

提交回复
热议问题