8

I know how to do it in C and Java, but I don't know a quick way of converting year/month/day/hour/min/second to the # of seconds since the Jan 1 1970 epoch.

Can someone help me?

So far I've figured out how to create a datetime object but I can't seem to get the elapsed # seconds since the epoch.

(edit: my question is the inverse of this other one: Python: Seconds since epoch to relative date)

Community
  • 1
  • 1
Jason S
  • 184,598
  • 164
  • 608
  • 970

5 Answers5

13

Use timetuple or utctimetuple method to get time tuple and convert it to timestamp using time.mktime

>>> import datetime
>>> dt = datetime.datetime(2011, 12, 13, 10, 23)
>>> import time
>>> time.mktime(dt.timetuple())
1323793380.0

There is a nice bug related to it http://bugs.python.org/issue2736, this is interesting read and anybody trying to convert to timestamp should read this. According to that thread correct way is

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • `mktime()` works only if `dt` is a local time. "correct way" works only if `dt` is a naive datetime object that represents time in UTC (it is wrong if `dt` is a local time). See [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/a/8778548/4279). – jfs Aug 20 '14 at 05:05
7

You can use datetime.datetime(1970, 1, 1) as a reference and get the total amount of seconds from a datetime.timedelta object as follows:

from datetime import datetime

delta = your_date - datetime(1970, 1, 1)
delta.total_seconds()
jcollado
  • 39,419
  • 8
  • 102
  • 133
3
import calendar

calendar.timegm(datetime_object.utctimetuple())
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • 1
    `utctimetuple()` fails silently if `datetime_object` has no timezone info attached unless `datetime_object` is already represents UTC time. – jfs Aug 20 '14 at 05:06
1

These lines can return a float number representing seconds since epoch.

import time

time.time()
Hanson
  • 254
  • 2
  • 10
1

To convert a datetime object (broken-downtime time: year/month/day/hour/min/second) to seconds since the Epoch (POSIX time):

seconds_since_epoch = datetime_object.timestamp()

Note: POSIX Epoch is "00:00:00 GMT, January 1, 1970".

If datetime_object has no timezone info then .timestamp() method uses a local timezone.

datetime.timestamp() method is introduced in Python 3.3; for code that works on older Python versions, see Converting datetime.date to UTC timestamp in Python.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670