python保存当前时间并保存到数据库
时间: 2023-12-20 09:04:33 浏览: 37
可以使用 Python 自带的 datetime 模块获取当前时间,然后使用数据库的 API 将时间保存到数据库中。
下面是一个示例,假设你使用的是 MySQL 数据库:
``` python
import datetime
import mysql.connector
# 获取当前时间
now = datetime.datetime.now()
# 连接数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
cursor = cnx.cursor()
# 准备 SQL 语句
sql = "INSERT INTO table_name (timestamp) VALUES (%s)"
# 执行 SQL 语句,将当前时间保存到数据库中
cursor.execute(sql, (now,))
# 提交事务
cnx.commit()
# 关闭数据库连接
cursor.close()
cnx.close()
```
这个示例中,我们使用了 datetime 模块获取当前时间,然后使用 MySQL 的 Python API 连接数据库并将当前时间保存到数据库中。这个示例中的 `table_name` 是指你要保存时间的表名,`timestamp` 是指保存时间的列名。你需要将这两个名称替换成你自己的表和列名。
相关问题
python爬取多页新闻全部信息并保存数据库
好的,这里是一个例子,它可以爬取多页新闻并将所有信息保存到数据库中。这个示例使用了requests库来发送HTTP请求,使用了BeautifulSoup库来解析HTML页面,使用了SQLite数据库来存储数据。假设每个新闻都有标题、内容和发布时间三个字段。
```python
import requests
from bs4 import BeautifulSoup
import sqlite3
# 定义要爬取的新闻网站的URL和总页数
base_url = 'http://www.example.com/news?page='
total_pages = 10
# 连接到SQLite数据库
conn = sqlite3.connect('news.db')
# 创建一个游标对象
cursor = conn.cursor()
# 创建一个表来存储新闻
cursor.execute('CREATE TABLE IF NOT EXISTS news (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, content TEXT, publish_time TEXT)')
# 循环遍历每一页
for page in range(1, total_pages + 1):
# 拼接当前页的URL
url = base_url + str(page)
# 发送HTTP请求并获取响应
response = requests.get(url)
# 使用BeautifulSoup解析HTML页面
soup = BeautifulSoup(response.content, 'html.parser')
# 找到新闻文章的列表
articles = soup.find_all('div', {'class': 'article'})
# 循环遍历每篇新闻文章
for article in articles:
# 获取新闻标题、内容和发布时间
title = article.find('h2').text.strip()
content = article.find('div', {'class': 'content'}).text.strip()
publish_time = article.find('span', {'class': 'time'}).text.strip()
# 将新闻标题、内容和发布时间插入到数据库中
cursor.execute('INSERT INTO news (title, content, publish_time) VALUES (?, ?, ?)', (title, content, publish_time))
conn.commit()
# 关闭游标和数据库连接
cursor.close()
conn.close()
```
在这个示例中,我们首先定义要爬取的新闻网站的URL和总页数。然后,我们连接到SQLite数据库,并创建一个表来存储新闻。接下来,我们循环遍历每一页,并发送HTTP请求并获取响应。使用BeautifulSoup解析HTML页面,并找到新闻文章的列表。循环遍历每篇新闻文章,获取新闻标题、内容和发布时间,并将它们插入到数据库中。最后,我们关闭游标和数据库连接。
请注意,这只是一个简单的示例,实际应用中可能需要更复杂的爬虫和数据库架构。同时,也要注意遵守网站的使用条款和法律法规,以确保合法合规。
python数据库时间更新
要更新Python中的数据库时间,您需要使用SQL语句中的UPDATE命令。以下是一个示例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建一个游标对象
mycursor = mydb.cursor()
# 更新一个特定的时间戳
sql = "UPDATE yourtable SET timestamp = NOW() WHERE id = 1"
mycursor.execute(sql)
# 确认更改
mydb.commit()
print(mycursor.rowcount, "记录更新")
```
在上面的示例中,我们使用NOW()函数将时间戳设置为当前日期和时间。您可以根据需要使用其他函数来设置不同的时间戳。请注意,在使用UPDATE命令更新数据库记录时,您需要使用commit()方法来保存更改。