Convert boto3 output to convenient format

boto3, datetime, python

Solution

This is almost certainly already the format you need. datetime objects are easily comparable / sortable. For example:

from datetime import datetime

import boto3


ec2 = boto3.client('ec2')
account_id = 'MY_ACCOUNT_ID'
response = ec2.describe_snapshots(OwnerIds=[account_id])
snapshots = response['Snapshots']

# January 1st, 2017
target_date = datetime(2017, 01, 01)

# Get the snapshots older than the target date
old_snapshots = [s for s in snapshots if s['StartTime'] < target_date]

# Sort the old snapshots
old_snapshots = sorted(old_snapshots, key=lambda s: s['StartTime'])

docs: https://docs.python.org/3.6/library/datetime.html

Problem

I am getting the below output using describe_snapshots function in boto3 u'StartTime': datetime.datetime(2017, 4, 7, 4, 21, 42, tzinfo=tzutc()) I wish to convert it into proper date so that I can proceed with sorting the snapshots and removing the ones which are older than a particular number of days. Is there a python functionality which can be used to attain this ?

Original source