1

i am currently using the time.time() command to calculate the current amount of seconds since the epoch, however could this be adapted to easily show the number of seconds since the epoch for a past date, I.E. 2014-03-14-18-00-00

Thanks

user2065929
  • 1,065
  • 4
  • 21
  • 35

2 Answers2

2

Python datetime module has the functionality to compute the total number of seconds since the epoch for a past date. For example if you want to compute the number of seconds 2014-03-14-18-00-00

epoch = datetime.datetime.strptime('2014-03-14-18-00-00', '%Y-%m-%d-%H-%M-%S')
# to compute current amount of seconds from epoch
total_seconds = (epoch - datetime.datetime.fromtimestamp(time.time())).total_seconds()
Abinash Panda
  • 454
  • 2
  • 7
  • 1
    This calculates the time from 2014-03-14-18-00-00 to the current time. The epoch in the context of the question is the [Unix time](http://en.wikipedia.org/wiki/Unix_time). – Roland Smith Mar 22 '15 at 17:07
2

Use time.mktime():

In [1]: import time

In [2]: target = time.strptime('2014-03-14-18-00-00', '%Y-%m-%d-%H-%M-%S')

In [3]: int(time.mktime(target))
Out[3]: 1394816400
Roland Smith
  • 42,427
  • 3
  • 64
  • 94