#author("2018-10-17T12:25:04+00:00","","")
* Pythonメモ [#c3ed5c17]
#author("2018-11-01T22:40:07+00:00","","")
* Python覚え書き [#c3ed5c17]
#setlinebreak(on)

#contents
-- 関連
--- [[Python]]
--- [[Pythonのインストール]]
--- [[Python のパッケージング]]
--- [[PythonでAWS DynamoDBのCRUDを書いてみる]]
--- [[Pythonのstrptimeが遅い]]
--- [[Pythonのチューニング]]
--- [[Pythonのパフォーマンス確認]]
--- [[FizzBuzzで頭の体操]]
--- [[pytest入門]]
--- [[OpenSSLで電子署名の生成と署名検証]]


** 日付文字列を datetime オブジェクトに変換する [#rf237495]
#html(<div style="padding-left: 10px;">)
#mycode2(){{
from datetime import datetime

date_text = '2018-01-01T01:02:03Z'
target_datetime = datetime.strptime(date_text, '%Y-%m-%dT%H:%M:%SZ')
}}
#html(</div>)

** datetime を 日付文字列に変換する [#c130a1e2]
#html(<div style="padding-left: 10px;">)
#mycode2(){{
from datetime import datetime

target_datetime = datetime.now()
date_text = target_datetime.strftime('%Y-%m-%dT%H:%M:%SZ')
}}
#html(</div>)

** 日付の加算 [#z0ebfe02]
#html(<div style="padding-left: 10px;">)
#mycode2(){{
from datetime import datetime
from datetime import timedelta

target_date = datetime.now()
time_minutes = timedelta(minutes=int(minutes))
print(target_date + time_minutes)
}}

#html(</div>)


** 日時を年月日単位で切り捨てる [#n0f5aacf]
#html(<div style="padding-left: 10px;">)
datetime.timetuple で取得したタプルを、datetimeの引数に指定する事により、切り捨てられたdatetimeが得られる。
#mycode2(){{
from datetime import datetime

def trunc_date(target_date):
    """ 
    日時を年月日単位で切り捨てる
    """
    now_date_tuple = target_date.timetuple()[:3]  # 年月日のタプルを取得
    #now_date_tuple = target_date.timetuple()[:4]  # 年月日時のタプルを取得
    #now_date_tuple = target_date.timetuple()[:5]  # 年月日時分のタプルを取得
    return datetime(*now_date_tuple)

print(trunc_date(datetime.now()))

}}
#html(</div>)

** With構文を使用して開始、終了処理を行う [#g1a8cbd7]
#html(<div style="padding-left: 10px;">)

__enter__ 及び __exit__ メソッドを持つクラスを with 構文と共に利用することで、開始、終了処理を行う事ができる。

sample_with.py
#mycode2(){{
# coding: utf-8

class SampleWith(object):
    def __init__(self):
        print('\t with class init')

    def __enter__(self):
        # 開始処理
        print('\t with class enter')

    def __exit__(self, exc_type, exc_value, tb):
        # 終了処理
        print('\t with class exit')


if __name__ == '__main__':
    print('start')
    with SampleWith() as sample:
        print('\t\t internal start')
        for i in range(10):
            print(f'\t\t\t point {i:05d}')
        print('\t\t internal end')
    print('end')
}}

実行結果
#myterm2(){{
$python3 sample_with.py
start
	 with class init
	 with class enter
		 internal start
			 point 00000
			 point 00001
			 point 00002
			 point 00003
			 point 00004
			 point 00005
			 point 00006
			 point 00007
			 point 00008
			 point 00009
		 internal end
	 with class exit
end
}}
#html(</div>)


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS