
を参考にしているブログ一覧 投稿一覧へ戻る
Python Cookbook [3.15. Converting Strings into Datetimes : 文字列を Datetime 型へ変換する]
Published 2020年4月21日18:59 by T.Tsuyoshi
Problem: 日付形式の文字列を datetime オブジェクトへ変換したい。 Solution: Python 標準の datetime モジュールの利用で簡単に実現できます。 from datetime import datetime text = "2020-04-21" a = datetime.strptime(text, '%Y-%m-%d') b …Python Cookbook [Finding the Date Range for the Current Month : その月は何日まで?]
Published 2020年4月18日18:17 by T.Tsuyoshi
Problem: ある月の全ての日を簡単にループ処理したい。 Solution: 対象となる月の日数分のリストを用意するような必要はありません。 開始日(その月の1日)と終了日(翌月の1日)を取得し、datetime.timedelta オブジェクトを利用してその間を1日ずつループしていきます。 from datetime import datetime, date, ti…Python Cookbook [Determining Last Friday's Date : 前の金曜日は何日?]
Published 2020年4月16日19:16 by T.Tsuyoshi
Problem : 直前のある曜日 (例えば前の金曜日とか) が何日だったかを知りたい。 Solution : Python の datetime モジュールには、こういった際の計算に使用できるユーティリティ関数やクラスが含まれています。 それらを利用して次のような関数を用意することが一般的な対処方法でしょう。 from datetime import datetime…Python Cookbook [Converting Days to Seconds, and Other Basic Time Conversions : 日付の秒数への変換、及び、他の基本的な日時変換]
Published 2020年4月14日21:14 by T.Tsuyoshi
# Problem: # 日付を秒数、分数、時間に変換するような単純な日時変換を行いたい。 # Solution: # 異なる時間ユニット間の変換や計算には datetime モジュールを利用します。 # 例えば、2つの時間の差などの時間間の計算を実行したければ timedeltaオブジェクトを使用します。 from datetime import timedelta a…Python Cookbook [Picking Things at Random : random の活用]
Published 2020年4月13日19:58 by T.Tsuyoshi
# Problem: # シーケンスからランダムに要素を取り出したり、乱数を発生させたい。 # Solution: # random モジュールには様々な関数が用意されています。 # シーケンスからランダムに要素を取り出します。 import random values = ['Nana', 'Saki', 'Hana', 'Yuka', 'Megu', 'Eri', '…