alternative to total_seconds() in python 2.6

后端 未结 1 1786
不思量自难忘°
不思量自难忘° 2021-01-03 07:16

In python 2.7 there is the total_seconds() method.

In python 2.6, it doesn\'t exist and it suggests to use

(td.microseconds + (td.seconds + td.days          


        
1条回答
  •  心在旅途
    2021-01-03 07:53

    Here it is in a timedelta_total_seconds function and using 2.7 you can see that it gets the same output as using the total_seconds method.

    import datetime
    
    
    def timedelta_total_seconds(timedelta):
        return (
            timedelta.microseconds + 0.0 +
            (timedelta.seconds + timedelta.days * 24 * 3600) * 10 ** 6) / 10 ** 6
    
    
    timestamp = '2014-10-24 00:00:00'
    time_delta = datetime.datetime.strptime(
        timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970, 1, 1)
    
    print timedelta_total_seconds(time_delta)
    print time_delta.total_seconds()
    

    Outputs

    1414108800.0
    1414108800.0
    

    0 讨论(0)
提交回复
热议问题