from datetime import datetime
import click


def validate_optional_timestamp(ctx, param, value):
    """Ensure that a valid value for a timestamp is used."""

    if value:
        try:
            return datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(
                hour=0, minute=0, second=0
            )
        except ValueError:
            raise click.BadParameter(
                "{} must be a valid utc timestamp formatted as `%Y-%m-%dT%H:%M:%SZ` "
                "e.g. `2020-12-31T00:00:00Z`".format(param.name),
                param=param,
            )

    return value