Python を使用して MySQL データベースに日付を保存および取得するにはどうすればよいですか?

PHPz
リリース: 2023-09-14 22:37:02
転載
487 人が閲覧しました

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

MySQL データベースに日付を挿入するには、テーブルに Date または DateTime 型の列が必要です。完了したら、データベースに挿入する前に日付を文字列形式に変換する必要があります。これを行うには、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、日付) を挿入しようとします。

選択クエリを使用してデータベースから日付を取得する場合、strptime などの関数を使用して日付を解析して datetime オブジェクトに戻す必要があります。

Example

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')
ログイン後にコピー

これは作成日を取得し、それを datetime オブジェクトに解析します。

以上がPython を使用して MySQL データベースに日付を保存および取得するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!