I'm trying to get a list of venues to display, and then count the number of upcoming shows. I'm running into the error at filtered_upcomingshows = [show for show in upcomingshows if show.start_time > current_time]. The model has the start_time field set to DateTime, and current_time is set as DateTime (unless I'm misunderstanding how it's used?). I can't figure out which one is being read as a string. How would I fix this?
class Show(db.Model):
__tablename__ = 'shows'
id = db.Column(db.Integer, primary_key=True)
artist_id = db.Column(db.Integer, db.ForeignKey('artists.id'), nullable = False)
venue_id = db.Column(db.Integer, db.ForeignKey('venues.id'), nullable = False)
start_time = db.Column(db.DateTime, nullable = False)
def __repr__(self):
return '<Show {} {}>'.format(self.artist_id, self.venue_id)
@app.route('/venues')
def venues():
current_time = datetime.now().strftime('%Y-%m-%d %H:%S:%M')
venue_city_state = ''
data = []
# queries Venue db for all records
venues = Venue.query.all()
for venue in venues:
upcomingshows = venue.shows
filtered_upcomingshows = [show for show in upcomingshows if show.start_time > current_time]
if venue_city_state == venue.city + venue.state:
data[len(data) - 1]["venues"].append({
"id": venue.id,
"name": venue.name,
"num_upcoming_shows": len(filtered_upcomingshows)
})
else:
venue_city_state == venue.city + venue.state
data.append({
"city": venue.city,
"state": venue.state,
"venues": [{
"id": venue.id,
"name": venue.name,
"num_upcoming_shows": len(filtered_upcomingshows)
}]
})
The problem is (as the interpreter says) that current_time is a string and show.start_time is a datetime.datetime instance. To solve this issue you can just drop the .strftime('%Y-%m-%d %H:%S:%M') call when defining current_time.
date.strftime(format)Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see
strftime()andstrptime()Behavior.
Reference: https://docs.python.org/3/library/datetime.html#datetime.date.strftime
current_time = datetime.now().strftime('%Y-%m-%d %H:%S:%M')
.strftime is documented to return a string, just nix the call and it will work:
current_time = datetime.now()