Skip to content

Instantly share code, notes, and snippets.

@danielthiel
Last active February 12, 2021 13:06
Show Gist options
  • Select an option

  • Save danielthiel/8374607 to your computer and use it in GitHub Desktop.

Select an option

Save danielthiel/8374607 to your computer and use it in GitHub Desktop.
SQLAlchemy: filter by date for an datetime field(does not work with SQLite, with PostgreSQL it works fine)
from datetime import date
from sqlalchemy import cast, DATE
Match.query.filter(cast(Match.date_time_field, DATE)==date.today()).all()
@jonathanmach

jonathanmach commented Mar 12, 2018

Copy link
Copy Markdown

Hi guys,
For SQLite, I'm using the func.DATE() function:

from sqlalchemy import func

session.query(db.Transaction).filter(func.DATE(db.Transaction.datetime) == date.today())

@stuartmaxwell

Copy link
Copy Markdown

Hi guys,
For SQLite, I'm using the func.DATE() function:

from sqlalchemy import func

session.query(db.Transaction).filter(func.DATE(db.Transaction.datetime) == date.today())

I've been pulling my hair out trying to solve this, but your suggestion worked perfectly. Thanks!

@haanzee

haanzee commented Nov 13, 2019

Copy link
Copy Markdown

@bhandler.route('/sbooking', methods=['GET', 'POST'])
def sbooking():
form = SBookingForm()
if form.validate_on_submit():
s_date = form.bdate.data
sr_date = s_date.strftime("%Y-%m-%d %H:%M:%S")

	if form.bresort.data=='Sona Grand':
		rec = db.session.query(Booking).filter(Booking.bresort == 'Sona Grand'
			).filter(Booking.bauth == 'Yes'
			).filter(Booking.bdate == sr_date)
		return render_template('sbookingrec.html', rec=rec, sr_date=sr_date)
return render_template('sbooking.html', title='Date Status',
	form=form, legend='Date Status')

@haanzee

haanzee commented Nov 13, 2019

Copy link
Copy Markdown

sir when comparison with date return nothing but use less then and greater then code is working
problem with date comparison is not working

@arqeco

arqeco commented Jan 18, 2020

Copy link
Copy Markdown

Thank you Jonatan. func.DATE() works.
I've opened an issue sqlalchemy/sqlalchemy#5104

@AlejandroRodriguezP

Copy link
Copy Markdown

Hi guys,
For SQLite, I'm using the func.DATE() function:

from sqlalchemy import func

session.query(db.Transaction).filter(func.DATE(db.Transaction.datetime) == date.today())

It worked! Thank you sooo much!

@3yggy

3yggy commented Sep 9, 2020

Copy link
Copy Markdown

👺it doesn't work with even postgress for me

@FabricioPatrocinio

FabricioPatrocinio commented Feb 12, 2021

Copy link
Copy Markdown

This worked for me:

from sqlalchemy import func
table_db = Youtable.query.filter(func.DATE(Youtable.date_bd) == your_date)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment