8

I would like to convert a Python date object to a Unix timestamp.

I already added a time object, so it would be that specific date at midnight, but I don't know how to continue from there.

d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t)

#How to convert this to Unix timestamp?

I am using Python 2.7

JNevens
  • 11,202
  • 9
  • 46
  • 72
  • possible duplicate of [Converting datetime.date to UTC timestamp in Python](http://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python) – jfs Mar 27 '15 at 23:40

4 Answers4

16

You can get the unix time like this:

import time
from datetime import date

d = date(2014, 10, 27)

unixtime = time.mktime(d.timetuple())
Alex
  • 21,273
  • 10
  • 61
  • 73
5

Unix time can be derived from a datetime object like this:

d = date(2014, 10, 27)
t = time(0, 0, 0)
dt = datetime.combine(d, t) 

unix = dt.strftime('%s')
# returns 1414364400, which is 2014-10-27 00:00:00 
JNevens
  • 11,202
  • 9
  • 46
  • 72
1

You can use easy_date to make it easy:

import date_converter
timestamp = date_converter.date_to_timestamp(d)
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37
-2
>>> import datetime
>>> d = datetime.date(2014, 10, 27)
>>> int("{:%s}".format(d))
1414364400
>>> datetime.datetime.fromtimestamp(1414364400)
datetime.datetime(2014, 10, 27, 0, 0)

Please note that %s formatting of times is not supported on Windows.

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958