2

I have a query in SQLAlchemy:

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time.in_(week_dates),
        WeeklyHour.end_time.in_(week_dates),
        WeeklyHour.employee == employee
        )
    ).all()

I am getting the dates of the current week like so:

today = datetime.datetime.today()
week_dates = [today + datetime.timedelta(days=i) for i in xrange(0 - today.weekday(), 7 - today.weekday())]

This returns a list of the current week in datetimes. Like so:

[datetime.date(2014, 4, 7), datetime.date(2014, 4, 8), datetime.date(2014, 4, 9), datetime.date(2014, 4, 10), datetime.date(2014, 4, 11), datetime.date(2014, 4, 12), datetime.date(2014, 4, 13)]

The problem is that the WeeklyHour is a datetime when the employee started and ended that day. And week_dates are a specific time set to now(). I will never get results because the time of the datetime won't match. All I really want to compare is the date portion of the datetime. My current solution (which works but is dumb) is to store separate dates of the datetime.

1
  • what database do you use? Commented Apr 13, 2014 at 14:45

1 Answer 1

3

Rather than querying "in" all days of the week use the days as limits.

today = date.today()
start_of_week = today - timedelta(days=today.weekday())
start_of_following_week = start_of_week + timedelta(days=7)

weekly_schedule = WeeklyHour.query.filter(
    and_(
        WeeklyHour.start_time >= start_of_week,  # On or after Monday
        WeeklyHour.end_time < start_of_following_week, # Before next Monday
        WeeklyHour.employee == employee
        )
    ).all()
Sign up to request clarification or add additional context in comments.

1 Comment

As it happens, the and_() call surrounding all those conditions is not required as it's the default mode for .query.filter().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.