Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python date to Unix timestamp

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

like image 792
JNevens Avatar asked Mar 27 '15 10:03

JNevens


3 Answers

You can get the unix time like this:

import time
from datetime import date

d = date(2014, 10, 27)

unixtime = time.mktime(d.timetuple())
like image 70
Alex Avatar answered Oct 23 '22 18:10

Alex


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 
like image 33
JNevens Avatar answered Oct 23 '22 18:10

JNevens


You can use easy_date to make it easy:

import date_converter
timestamp = date_converter.date_to_timestamp(d)
like image 23
Raphael Amoedo Avatar answered Oct 23 '22 20:10

Raphael Amoedo