DynamoDBのTTL

The item must contain the attribute specified when TTL was enabled on the table.
The TTL attribute’s value must be a timestamp in Unix epoch time format in seconds.

ポイントは以下の2点だけ。

  • アイテムにはTTLにする属性を含める
  • TTL属性の値はUNIXエポックタイムにする

DynamoDBでTTL属性名を指定する

Cloudformationでの指定は以下。属性名expire_atをTTL属性名としている。

1
2
3
TimeToLiveSpecification:
AttributeName: "expire_at"
Enabled: "True"

UNIXエポックタイムの作り方

Pythonの場合は以下のように未来のdatetimeオブジェクトを作ってtimestamp()メソッドでUNIXエポックタイムに変えればいい。
あとはアイテムにエポックタイムでexpire_atとして値を設定すればOK。

import datetime

ttl_date = datetime.datetime.now() + datetime.timedelta(days=90) # 90日後
ttl = str(ttl_date.timestamp())
...