Python查询mycql数据库时间范围内数据
时间: 2023-09-22 19:07:28 浏览: 100
vb导出数据库数据
要在Python中查询MySQL数据库时间范围内的数据,可以使用以下步骤:
1. 导入MySQL驱动程序和时间库:
```python
import mysql.connector
from datetime import datetime, timedelta
```
2. 连接到MySQL数据库:
```python
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
cursor = cnx.cursor()
```
3. 构建SQL查询语句,使用`BETWEEN`操作符指定时间范围:
```python
query = ("SELECT * FROM your_table "
"WHERE your_datetime_column BETWEEN %s AND %s")
start_time = datetime(2021, 1, 1) # 起始时间
end_time = datetime(2021, 6, 30) # 结束时间
params = (start_time, end_time)
```
4. 执行查询并获取结果:
```python
cursor.execute(query, params)
result = cursor.fetchall()
```
5. 处理查询结果,关闭数据库连接:
```python
for row in result:
print(row)
cursor.close()
cnx.close()
```
完整代码示例:
```python
import mysql.connector
from datetime import datetime, timedelta
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
cursor = cnx.cursor()
query = ("SELECT * FROM your_table "
"WHERE your_datetime_column BETWEEN %s AND %s")
start_time = datetime(2021, 1, 1) # 起始时间
end_time = datetime(2021, 6, 30) # 结束时间
params = (start_time, end_time)
cursor.execute(query, params)
result = cursor.fetchall()
for row in result:
print(row)
cursor.close()
cnx.close()
```
阅读全文