はじめに
社員データや顧客データWorkatoで扱う際、誕生日や勤続年数、サービス継続年数、法人の事業年数など、何らかの経過年数などを取得したい場合があるかと思います。
年数の計算は閏年を考慮しなければならず、閏年とそうでない年では日数が異なるため、単純に時間や日数をもとに計算を行うことはできません。
Workatoにおいて年数の計算方法は様々ありますが、Pythonコネクタを利用すると、コードを書く必要はあるものの、シンプルに年数計算のための処理を用意することができます。また、Recipe Functionとして作成して共通処理化(モジュール化)することで、様々なレシピで共通して活用する(再利用性を高める)ことができます。
今回は、再利用性の観点から、Recipe Functionで年数計算処理の実装を進めていきます。
レシピ
Step1(トリガー)
- Parameter schemaに
date_from
date_to
をdate型で追加 - Result schemaに
year
を integer型で追加
Step2
Pythonコネクタを追加し、次の通り設定します。
Name
- 任意の値を入力します。
Input fields
-
date_from
date_to
をString型で追加します。 - Step1のParameter schemaのデータピル(
date_from
date_to
)を、対応するフィールドへ追加します。 - 各フィールドを formulaモードに切り替え、それぞれのデータピルの後ろに
.strftime("%Y-%m-%d")
を追加します。
Output fields
-
year
をInteger
型で追加します。
Code
from datetime import datetime
def main(input):
date_format = '%Y-%m-%d'
date1 = datetime.strptime(input['date_from'], date_format)
date2 = datetime.strptime(input['date_to'], date_format)
years_difference = date2.year - date1.year
if (date2.month, date2.day) < (date1.month, date1.day):
years_difference -= 1
return {'year': years_difference}
Step 3
yearフィールドに、Step2のyear
データピルを追加します。
実行結果
Test recipe で次の条件を設定してレシピをテスト実行すると、指定された日付間の年数が結果として返されます。