如何使用python在sqlite数据库中搜索日期?

2024-10-02 20:39:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据库(名为“all峎ubokings”),其中有一个名为“date”的列,在一个名为“bookings”的表中,该表以“dd/mm/yyyy”的形式存储日期,例如“16/10/2017”。我想用python编写一个函数来搜索特定月份的所有日期,并将其输出。例如,如果在存储在“2017年12月12日”、“2018年11月23日”和“2018年12月19日”的日期中,我希望输出12月的所有日期,我将如何执行此操作?我知道如何搜索一个特定的日期,只是不是一个特定的月份。如有任何帮助,我们将不胜感激。谢谢


Tags: 函数数据库datealldd形式mm月份
1条回答
网友
1楼 · 发布于 2024-10-02 20:39:30

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)

结果是:

^{pr2}$

相关问题 更多 >