Question

I am having problem getting some datetime conversions. I am actually using django and in one of model field I used date field not datetime field. Now I need to show time difference and I got the snippet for that from djangosnippets. But that accepts timestamp.

So I am confuse that what actually is python timestamp and how can it be made. I tried different things as in below lines:

publish_date.timetuple()

but this says, that 'datetime.date' object has no attribute 'mktime'.I guess datetime.datetime has this mktime but not datetime.date so I can't use that.

int(parse(publish_date).strftime('%s'))

Here parse is from a third party module named dateutil but this time it gives following error.

datetime.date' object has no attribute 'read'

And it gives same error for following code:

humanizeTimeDiff(publish_date)

So any better idea or approach that I should try to convert datetime.date object to timestamp. It seems like converting datetime.datetime would be also helpful. But how ?

Was it helpful?

Solution

Since you don't have any time information in your database (only date), you can only calculate the difference in number of days. To do that, simply subtract the date objects. This will yield a timedelta object which represents the difference between two date (or datetime) objects.

>>> d1
datetime.date(2012, 9, 16)
>>> d2
datetime.date(2012, 9, 17)
>>> d2-d1
datetime.timedelta(1)
>>> print d2-d1
1 day, 0:00:00
>>> print (d2-d1).days
1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top