LoginSignup
0
4

More than 3 years have passed since last update.

pythonでべたに使うもの(python3)

Posted at

目的

pythonをちょこちょこ調べらながら書いていて、今後も使用するであろうものをまとめる。
※初心者向け

dict(辞書)からキーがなくても落ちない方法

下記のようにdictから取得すると実行時にエラーが発生してしまう。

dict = {}
print(dict['test'])
実行結果
Traceback (most recent call last):
  File "sample.py", line 2, in <module>
    print(dict['test'])
KeyError: 'test'

dictのgetメソッドを使用することで、キーがなくてもエラーにならずにNoneが返却される。

dict = {}
print(dict.get('test'))
実行結果
None

数値のチェック

# 数値であるかチェックします。
# 半角数値、少数の場合Trueを返します。
def isNum(num):
    return re.compile('^([1-9]\\d*|0)(\\.\\d+)?$').match(num) is not None

正の整数のチェック

# 正の整数(0を除く)であるかチェックします。
# 正の整数(0を除く)である場合Trueを返します。
def isPlusInteger(num):
    return re.compile('^[1-9]\\d*$').match(num) is not None

少数第1位で切り捨て

from decimal import Decimal,ROUND_DOWN

def roundDown(val):
    return Decimal(val).quantize(Decimal('0.1'), rounding=ROUND_DOWN)

少数を整数に切り捨て

from decimal import Decimal

# 整数に切り捨てます。
def truncateNum(val):
    return str(math.floor(Decimal(val)))

日付のフォーマット

from datetime import datetime

# YYYYMMDDをYYYY/MM/DDの形式にフォーマットします。
def dayFormat(day):
    return datetime.strptime(day, '%Y%m%d').strftime('%Y/%m/%d')

AWSで日本時間で現在日時を取得します。

def getNowTime():
    # AWSの時刻は、UTCなのでJSTに変換
    return datetime.now(timezone(timedelta(hours=+9), 'JST'))

最後に

メソッド名のセンスのなさが悩み。

0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4