AWS

How to Store Timestamps in DynamoDB

Timestamps are one of the most vital database features and a task worth mastering. DynamoDB also features various ways of representing and storing a timestamp. More obviously, you can conveniently store timestamps in DynamoDB as table attributes.

You can either store a timestamp as a Number data type or a String data type. Timestamps stored as a Number data type have a Unix timestamp value (seconds or milliseconds), while those stored as String data types feature the ISO 8601 string formats.

Ideally, working with timestamps also requires unbeatable precision. The more precise your timestamps are, the easier they are to query. For example, you can specify the year of creation for each item on your table or get more specific by stating the minute, second, or millisecond. The more specific your timestamps are, the easier they will be to sort, query, or filter.

Store Timestamps in DynamoDB Using the Number Data Type

You can use the Number data type to store a timestamp. In this illustration, our Number data type will take the form of a date attribute. A Boto3 (AWS SDK for Python) example of how to store a timestamp in DynamoDB is as follows:

import boto3
import datetime

# Create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# Get the current timestamp
timestamp = int(datetime.datetime.utcnow().timestamp())

# Create a new item in your table
response = dynamodb.put_item(
TableName='my-table-name',
    Item={
        'id': {'N': '1234'},
        'timestamp': {'N': str(timestamp)}
    }
)

The data type for the above timestamp stores the number in seconds since the midnight of January 1, 1970, which is the epoch. Of course, it will also use the UTC time zone.

Retrieve a Timestamp in DynamoDB

Retrieving a timestamp in DynamoDB is not a complex undertaking. Like every other retrieval operation in DynamoDB, you will use the get_item command on the client end to retrieve timestamps. An example command is shown below:

import boto3

# Create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# Retrieve the item from your table
response = dynamodb.get_item(
TableName='my-table-name',
    Key={
        'id': {'N': '1234'}
    }
)

# Get the timestamp from the item
item = response['Item']
timestamp = int(item['timestamp']['N'])

Convert a Timestamp Into a Datetime Object

You can further convert your timestamp into a datetime object using the datetime module. See the illustration below:

import datetime

# Convert the timestamp to a datetime object
dt = datetime.datetime.fromtimestamp(timestamp)
print(dt)

Store a Timestamp with a Updated_at Attribute

Interestingly, you can also store a timestamp in DynamoDB with an Updated_at attribute. In this example, we will set our Updated_at attribute to 2023-01-01.

import boto3

# Create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# Set the timestamp to 2023-01-01
timestamp = "2023-01-01"

# Set the table name
table_name = "my_table-name"

# Set the primary key
pk = "1234"

# Set the value to be stored
value = "happy new year"

# Set the attribute map
attribute_map = {
    "updated_at": {
        "S": timestamp
    },
    "value": {
        "S": value
    }
}

# Put the item in the table
response = dynamodb.put_item(
TableName=table_name,
    Item={
        "pk": {
            "S": pk
        },
        **attribute_map
    }
)

print(response)

The above example will store an item with a primary key of 1234 and two attributes: updated_at and value. The updated_at attribute will be set to the timestamp 2023-01-01, and the value attribute will be set to the string “happy new year.”

Query DynamoDB Between Two Timestamps

You can query items from a DynamoDB table with a updated_at attribute between two timestamps. To achieve this, use the query operation and specify the KeyConditionExpression parameter.

Here is an example of how you can query for items with an updated_at attribute between 2022-01-01 and 2022-12-31:

import boto3

# Create a DynamoDB client
dynamodb = boto3.client('dynamodb')

# Set the table name
table_name = "my_table_name"

# Set the start and end timestamps
start_timestamp = "2022-01-01"
end_timestamp = "2022-12-31"

# Query the table
response = dynamodb.query(
TableName=table_name,
KeyConditionExpression="updated_atBETWEEN :start_timestamp AND :end_timestamp",
ExpressionAttributeValues={
":start_timestamp": {
            "S": start_timestamp
        },
":end_timestamp": {
            "S": end_timestamp
        }
    }
)

# Print the query results
print(response)

The above code will return all items in the table that have an updated_at attribute between 2022-01-01 and 2022-12-31, inclusive. The KeyConditionExpression parameter specifies the condition that must be met for an item to be returned, and the ExpressionAttributeValues parameter sets the values for the attribute placeholders in the KeyConditionExpression.

You can also use the ScanIndexForward parameter to specify the order in which the items should be returned. By default, the ScanIndexForward parameter is set to True, which means that the items will be returned in ascending order. If you set it to False, the items will be returned in descending order.

Conclusion

This article discussed the basics of storing timestamps in DynamoDB. You can now store timestamps correctly in DynamoDB. We also highlighted how you could work with timestamps. Like every DynamoDB operation, you can use timestamps through your preferred AWS SDK or AWS CLI.

About the author

Kennedy Brian

Brian is a computer scientist with a bias for software development, programming, and technical content development. He has been in the profession since 2015. He reads novels, jogs, or plays table tennis whenever not on gadgets. He is an expert in Python, SQL, Java, and data and network security.