[Tutor] Datetime objects
Luke Thomas Mergner
lmergner at gmail.com
Sat Mar 17 00:48:05 CET 2012
Hi,
I am having trouble comparing two datetime objects. Using Sqlalchemy I save a string as a date into an sqlite field (which has no native date format, I gather).
> import datetime as dt
> date_obj = dt.datetime.strptime(date_string,'%m.%d.%Y')
I want to compare that date later with an inputed date, which I created with strptime(). This function is only available for datetime.datetime.strptime() not datetime.date
> >>> compare_date = dt.datetime.strptime('2011-01-27', '%Y-%m-%d')
> >>> print compare_date
> datetime.datetime(2012, 1, 27, 0, 0)
Despite the fact that I don't care about the time fields, they still get added. It appears that I can get at the date object returned in an sqlalchemy object:
> >>> for row in query_object:
> ... type(row.date)
> ...
> 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date
> FROM posts
> 2012-03-16 19:18:18,420 INFO sqlalchemy.engine.base.Engine ()
> <type 'datetime.date'>
> <type 'datetime.date'>
> <type 'datetime.date'>
But when I compare them, it always returns false because datetime.date does not seem to compare to datetime.datetime...
> >>> for row in q1:
> ... print type (row.date), row.date, ' vs ', type(compare_date), compare_date, row.date == compare_date
> ...
> 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine SELECT posts.date AS posts_date
> FROM posts
> 2012-03-16 19:33:56,011 INFO sqlalchemy.engine.base.Engine ()
> <type 'datetime.date'> 2011-11-05 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2011-11-29 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2011-12-23 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2012-01-18 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2012-01-17 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2012-01-27 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
> <type 'datetime.date'> 2012-01-14 vs <type 'datetime.datetime'> 2012-01-27 00:00:00 False
Can anyone help me out here? Thanks in advance.
PS: I'm asking here since I think this is a simple object comparison question, not a question specific to a library (sqlalchemy). If it matters, I'm playing around with a small web log application built on Werkzeug, Sqlalchemy, and Jinja2. I'm actually very impressed with the progress I've made.
Luke Mergner
Mechanicsville, MD
lmergner at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120316/06f248e5/attachment.html>
More information about the Tutor
mailing list