You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的boto3在DynamoDB自动填充时间戳?创建项时能否条件存储时间戳?

Answers to Your DynamoDB Timestamp Questions with Boto3

Hey there! Since you're familiar with the AWS Java SDK's @DynamoDBAutoGeneratedTimestamp annotation, let's walk through how to replicate (and extend) that functionality using Python's boto3, plus tackle your conditional timestamp question.


1. Auto-populating Timestamps in DynamoDB with Boto3

Unlike the Java SDK's annotation-based auto-generation, boto3 doesn't have a built-in annotation system—but there are several straightforward ways to automate timestamp handling:

Option 1: Manual Injection (Simplest & Most Common)

Just generate the timestamp directly in your code when creating/updating items. Use UTC time to avoid timezone issues, and store it as an ISO 8601 string or Unix timestamp (ISO strings are more human-readable).

import boto3
from datetime import datetime

# Initialize DynamoDB resource
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("YourTableName")

# Insert a new item with created_at and updated_at timestamps
response = table.put_item(
    Item={
        "id": "unique-item-id-123",
        "data": "Sample content",
        "created_at": datetime.utcnow().isoformat(),
        "updated_at": datetime.utcnow().isoformat()
    }
)

# Update an item and refresh the updated_at timestamp
response = table.update_item(
    Key={"id": "unique-item-id-123"},
    UpdateExpression="SET data = :new_data, updated_at = :now",
    ExpressionAttributeValues={
        ":new_data": "Updated content",
        ":now": datetime.utcnow().isoformat()
    }
)

Option 2: Automate with DynamoDB Streams + Lambda

If you want to avoid adding timestamp logic to your main code, you can use DynamoDB Streams to trigger a Lambda function whenever an item is created/updated. The Lambda can then backfill the timestamp for you.

  • Enable streams on your DynamoDB table (choose "New and old images" capture mode)
  • Create a Lambda function that listens to the stream, checks if created_at is missing on new items, and adds it using update_item

This is a "set-it-and-forget-it" approach, but note it adds a small latency since the timestamp is added after the initial item write.


2. Conditionally Saving Timestamps in DynamoDB

Absolutely! DynamoDB's Condition Expressions let you control exactly when a timestamp (or any attribute) is saved. Here are common use cases:

Case 1: Only Set created_at When Creating a New Item

Ensure created_at is only added once, when the item is first inserted (never overwritten on updates):

# Insert item ONLY if it doesn't exist, and set created_at/updated_at
response = table.put_item(
    Item={
        "id": "unique-item-id-123",
        "data": "New conditional item",
        "created_at": datetime.utcnow().isoformat(),
        "updated_at": datetime.utcnow().isoformat()
    },
    ConditionExpression="attribute_not_exists(id)"  # Fails if item already exists
)

Case 2: Only Update updated_at When Specific Conditions Are Met

For example, only update the timestamp if the item exists, or if the current updated_at is older than a certain time:

# Update item ONLY if it exists, and refresh updated_at
response = table.update_item(
    Key={"id": "unique-item-id-123"},
    UpdateExpression="SET data = :new_data, updated_at = :now",
    ConditionExpression="attribute_exists(id)",  # Fails if item doesn't exist
    ExpressionAttributeValues={
        ":new_data": "Conditionally updated content",
        ":now": datetime.utcnow().isoformat()
    }
)

# More granular: Only update if the existing updated_at is older than a specific time
response = table.update_item(
    Key={"id": "unique-item-id-123"},
    UpdateExpression="SET data = :new_data, updated_at = :now",
    ConditionExpression="updated_at < :cutoff_time",
    ExpressionAttributeValues={
        ":new_data": "Time-gated update",
        ":now": datetime.utcnow().isoformat(),
        ":cutoff_time": "2024-05-20T12:00:00.000Z"
    }
)

Quick Recap

  • Boto3 doesn't have direct annotation support like the Java SDK, but manual timestamp injection or Lambda/Streams can replicate auto-generation.
  • Conditional timestamps are fully supported using DynamoDB's Condition Expressions—you can enforce exactly when timestamps are set or updated.

内容的提问来源于stack exchange,提问作者David Neale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:21:40