boto3: Convert AMI Creation Date from string to Python datetime

When retrieving the AMI Creation Date from boto3 it returns a string data type. Visually, this is okay but it is challenging to do operations and comparisons to the AMI Creation Date like if the date is before or after a certain date.

To solve the issue we need to convert the AMI Creation Date from type string to datetime before we could do some operations.

The AMI Creation Date string looks like <strong><span style="color:#e53b51" class="tadv-color">2019-09-18T07:34:34.000Z</span></strong>. To convert this we need to use the strptime function from the datetime.datetime library.

TL;DR: Below is a Python code to convert a boto3 AMI Creation Date string to datetime.

from datetime import datetime

ami_creation_date_str = ami_details['CreationDate']

ami_creation_date = datetime.strptime(ami_creation_date_str, "%Y-%m-%dT%H:%M:%S.%fZ")

Below are examples on how to use the conversion with boto3 EC2 Client and boto3 EC2 Service Resource.

Using Boto3 EC2 Client

import boto3
from datetime import datetime

AMI_ID = 'ami-5n0x0myrj8wl8kpud'

ec2_client = boto3.client('ec2')

ami_details_list = ec2_client.describe_images(ImageIds=[AMI_ID], Owners=['self'])['Images']
ami_details = ami_details_list[0]

ami_creation_date_str = ami_details['CreationDate']

print(ami_creation_date_str)
print(type(ami_creation_date_str))

ami_creation_date = datetime.strptime(ami_creation_date_str, "%Y-%m-%dT%H:%M:%S.%fZ")

print(ami_creation_date)
print(type(ami_creation_date))

Using Boto3 EC2 Service Resources

import boto3
from datetime import datetime
    
AMI_ID = 'ami-5n0x0myrj8wl8kpud'

ec2_resource = boto3.resource('ec2')

ami_details = ec2_resource.Image(AMI_ID)

ami_creation_date_str = ami_details.creation_date

print(ami_creation_date_str)
print(type(ami_creation_date_str))

ami_creation_date = datetime.strptime(ami_creation_date_str, "%Y-%m-%dT%H:%M:%S.%fZ")

print(ami_creation_date)
print(type(ami_creation_date))

Let me know in the comments section if the above helped. You can also comment your use case and let me solve your issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.