How do I shift the decimal place in Python?

前端 未结 3 1050
情话喂你
情话喂你 2020-12-20 21:11

I\'m currently using the following to compute the difference in two times. The out - in is very fast and thus I do not need to display the hour and minutes which are just 0.

相关标签:
3条回答
  • 2020-12-20 21:21

    or use the datetime module

    >>> import datetime
    >>> a = datetime.datetime.strptime("30 Nov 11 0.00.00", "%d %b %y %H.%M.%S")
    >>> b = datetime.datetime.strptime("2 Dec 11 0.00.00", "%d %b %y %H.%M.%S")
    >>> a - b
    datetime.timedelta(-2)
    
    0 讨论(0)
  • 2020-12-20 21:29

    Expanding upon the accepted answer; here is a function that will move the decimal place of whatever number you give it. In the case where the decimal place argument is 0, the original number is returned. A float type is always returned for consistency.

    def moveDecimalPoint(num, decimal_places):
        '''
        Move the decimal place in a given number.
    
        args:
            num (int)(float) = The number in which you are modifying.
            decimal_places (int) = The number of decimal places to move.
        
        returns:
            (float)
        
        ex. moveDecimalPoint(11.05, -2) returns: 0.1105
        '''
        for _ in range(abs(decimal_places)):
    
            if decimal_places>0:
                num *= 10; #shifts decimal place right
            else:
                num /= 10.; #shifts decimal place left
    
        return float(num)
    
    print (moveDecimalPoint(11.05, -2))
    
    0 讨论(0)
  • 2020-12-20 21:40

    The same way you do in math

    a = 0.01;
    a *= 10; // shifts decimal place right
    a /= 10.; // shifts decimal place left
    
    0 讨论(0)
提交回复
热议问题