LoginSignup
6
4

More than 5 years have passed since last update.

AWSのtimestampと仲良くする

Posted at

前置き

CloudWatchからSNS経由でLambdaにデータを渡した際に時刻フォーマットがUTCなので、それと戦う

作った便利関数

def utc_to_jst(str_utc, date_format='%Y-%m-%d %H:%M:%S'):
    time = datetime.datetime.strptime(str_utc, '%Y-%m-%dT%H:%M:%S.%f%z')
    # UTC と JST の時差は+9時間だから9時間加算
    time += datetime.timedelta(hours=9)
    return time.strftime(date_format)

使い方

このutc_to_jst関数にawsのstr_utcを第一引数に渡すと、%Y-%m-%d %H:%M:%Sフォーマットの文字列に変換して吐き出してくれる

サンプル

>>> import datetime

>>> def utc_to_jst(str_utc, date_format='%Y-%m-%d %H:%M:%S'):
...     time = datetime.datetime.strptime(str_utc, '%Y-%m-%dT%H:%M:%S.%f%z')
...     time += datetime.timedelta(hours=9)
...     return time.strftime(date_format)
...
>>> utc_to_jst('2018-03-08T07:23:38.636+0000')

'2018-03-08 16:23:38'
6
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
6
4