2022年3月19日土曜日

EventBridgeのevent["time"]をdatetimeで処理する

 event = {'version': '0', 'id': '11111111-aaaa-bbbb-cccc-1111111111', 'detail-type': 'Scheduled Event', 'source': 'aws.events', 'account': '111122223333', 'time': '2022-3-01T06:00:00Z', 'region': 'ap-northeast-1', 'resources': ['arn:aws:events:ap-northeast-1:111122223333:rule/rule-test'], 'detail': {}}


EventBridgeからのeventがこんな感じで、timeを使いたいときのメモ。tzinfoを入れると、出力が変わります。

 

import datetime
from datetime import timedelta
from dateutil import tz

JST = tz.gettz('Asia/Tokyo')
UTC = tz.gettz("UTC")

def get_times(event, delta_minutes):
    dt = datetime.datetime.strptime(event["time"], "%Y-%m-%dT%H:%M:%SZ")
    # dt has no timezone
    print(f'event["time"]: {dt}')
    # set tzinfo
    t1 = dt.replace(tzinfo=JST)
    t2 = t1 - timedelta(minutes=delta_minutes)
    print(t1,t2)
    # set tzinfo
    t3 = dt.replace(tzinfo=UTC)
    t4 = t3 - timedelta(minutes=delta_minutes)
    print(t3,t4)
    
    return t1, t2, t3, t4

get_times(event, 24 * 60)

event["time"]: 2022-03-01 06:00:00
2022-03-01 06:00:00+09:00 2022-02-28 06:00:00+09:00
2022-03-01 06:00:00+00:00 2022-02-28 06:00:00+00:00
(datetime.datetime(2022, 3, 1, 6, 0, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Tokyo')),
 datetime.datetime(2022, 2, 28, 6, 0, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Tokyo')),
 datetime.datetime(2022, 3, 1, 6, 0, tzinfo=tzfile('/usr/share/zoneinfo/UTC')),
 datetime.datetime(2022, 2, 28, 6, 0, tzinfo=tzfile('/usr/share/zoneinfo/UTC')))

0 件のコメント:

コメントを投稿