from datetime import datetime
import pytz


def time_to_string_if_valid(t):
    """ Validate event_time according to EventAPI Specification."""

    if t is None:
        return datetime.now(pytz.utc).isoformat()

    if type(t) != datetime:
        raise AttributeError("event_time must be datetime.datetime")

    if t.tzinfo is None:
        raise AttributeError("event_time must have tzinfo")

    # EventServer uses milliseconds, but python datetime class uses micro. Hence
    # need to skip the last three digits.
    # pat: from PIO return t.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + t.strftime("%z")
    return t.isoformat()