André
André

Reputation: 25554

How to convert date to timestamp using Python?

I need to convert this result to timestamp:

>>> print (datetime.date(2010, 1, 12) + datetime.timedelta(days = 3))
2010-01-15

I need to compare the value with this timestamp:

>>> datetime.datetime.now()
2011-10-24 10:43:43.371294

How can I achieve this?

Upvotes: 2

Views: 3892

Answers (3)

Wieland
Wieland

Reputation: 1681

datetime.datetime.now() will return an instance of datetime.datetime which has a date() method returning an instance of datetime.date. You can then compare that to the result of datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)

Upvotes: 1

Constantinius
Constantinius

Reputation: 35059

I need to convert this result to timestamp

import time


mydate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)
time.mktime(mydate.timetuple())

I need to compare the value with this timestamp:

a = datetime.datetime(2010, 1, 12) + datetime.timedelta(days = 3)
b = datetime.datetime.now()

a < b 
a > b 
a == b 

Upvotes: 8

eumiro
eumiro

Reputation: 212885

oneDate = datetime.date(2010, 1, 12) + datetime.timedelta(days = 3)
now = datetime.datetime.now()

The first is date, the second is datetime. So if you just want to compare the dates (day, month, year), convert the second to date:

oneDate < now.date()

returns True

Upvotes: 1

Related Questions