如何使用 Python 在 MySQL 数据库中存储和检索日期?

PHPz
풀어 주다: 2023-09-14 22:37:02
앞으로
487명이 탐색했습니다.

如何使用 Python 在 MySQL 数据库中存储和检索日期?

要在 MySQL 数据库中插入日期,您的表中需要有一列类型为日期或日期时间的列。完成后,您需要将日期转换为字符串格式,然后再将其插入数据库。为此,您可以使用 datetime 模块的 strftime 格式化函数。

示例

from datetime import datetime
now = datetime.now()
id = 1
formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('insert into table(id, date_created) values(%s, %s)', (id, formatted_date))
로그인 후 복사

运行此命令将尝试将元组(id,date)插入到您的表中。

当您使用select查询从数据库中获取日期时,您需要使用strptime等函数将其解析回datetime对象。

示例

from datetime import datetime
# Assuming you have a cursor named cursor you want to execute this query on:
cursor.execute('select id, date_created from table where id=1')
# if you inserted the row above, you can get it back like this
id, date_str = cursor.fetchone()
# date is returned as a string in format we sent it as. So parse it using strptime
created_date = datetime.strptime(date_created, '%Y-%m-%d %H:%M:%S')
로그인 후 복사

这将获取创建日期并将其解析为日期时间对象。

위 내용은 如何使用 Python 在 MySQL 数据库中存储和检索日期?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:tutorialspoint.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!