Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to total_seconds() in python 2.6

Tags:

python

time

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 * 24 * 3600) * 10**6) / 10**6

Could somebody show me how to implement it below?

Thanks

import datetime

timestamp = '2014-10-24 00:00:00'
timestamp = int((datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970,1,1)).total_seconds())
print timestamp

timestamp = '2014-10-24 00:00:00'
timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S') - datetime.datetime(1970,1,1)
print timestamp
like image 914
scalauser Avatar asked Dec 05 '22 04:12

scalauser


1 Answers

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
like image 169
Yoriz Avatar answered Dec 06 '22 18:12

Yoriz