我有一个数据库(名为' all_bookings'),在名为'预订'的表格中有一个名为' date'的列。它将日期存储在< dd / mm / yyyy'形式,例如' 16/10/2017。'我想在python中编写一个函数来搜索特定月份的所有日期,然后输出它们。例如,如果存储在' 12/12 / 2017',23/11/2018'和' 19/12 / 2018'的日期中,我想输出12月的所有日期,我该怎么做?我知道如何搜索特定日期,而不是特定月份。任何帮助都将很高兴。感谢
答案 0 :(得分:0)
SUBSTR功能可以满足你的需要。修改为执行OP评论中提到的内容。
import sqlite3
conn = sqlite3.connect(':memory:')
events = [
('12/12/2017', 'ev_1'),
('23/11/2018', 'ev_2'),
('19/12/2018', 'ev_3'),
]
conn.execute('CREATE TABLE bookings (date, event)')
conn.executemany('INSERT INTO bookings (date, event) values (?,?)', events)
validMonth = False
while not validMonth:
lookForMonth = input('What month, please? (number from 1 through 12):')
try:
validMonth = 1<=int(lookForMonth)<=12
except:
pass
sqlCmd = 'SELECT date FROM bookings WHERE SUBSTR(date,4,2)="%.2i"' % int(lookForMonth)
for row in conn.execute(sqlCmd):
print (row)
结果是:
('12/12/2017',)
('19/12/2018',)