from datetime import datetime
from typing import Union
import pytz


def datetime_to_str(date: datetime, format_str: str) -> Union[str, None]:
    """Get date string from datetime, based on `format_str` provided.
    If `date` is already a string, return it. Make the date aware."""
    if isinstance(date, str):
        return date
    try:
        # We need the date to be aware, or the string won't be accepted by API
        try:
            return pytz.utc.localize(date).strftime(format_str)
        except ValueError:  # Already localized
            return date.strftime(format_str)
    except (TypeError, AttributeError):
        return None