Search code examples
aws-lambdaamazon-dynamodbboto3aws-appsynciso8601

Setting AWSDateTime for AppSync in AWS lambda function written in Python


I have a lambda function that needs to store an item in a DynamoDB table that is going to be used by AppSync. I want to add a createdAt and a updatedAt field to the item, as AWSDateTime types, and set them to the time of their creation. As explained here I need to use An extended ISO 8601 date and time string in the format YYYY-MM-DDThh:mm:ss.sssZ. I use:

import datetime from datetime
datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')

but what it gives me is something like 2022-03-26T18:23:47Z instead of 2022-03-26T18:23:47.210Z for example (The three number-places after the second are absent).

Could you please help me fix this?


Solution

  • Milliseconds are optional. Reduced precision formats are valid ISO 8601 timestamps and thus valid AWSDateTime types.

    If milliseconds are meaningful to your use case, there are several ways to add them:

    datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    datetime.now().isoformat(timespec='milliseconds') + 'Z'
    
    # '2022-03-27T11:05:10.351Z'