from pytz import UTC
from pytz import timezone as Timezone
from pytz.tzinfo import DstTzInfo


def dt_to_other_timezone(dt, destination_timezone_name, origin_timezone_name='UTC'):
    """
    The only, safest, way I know to convert datetime object from one timezone to
    another while accounting for things like Daylight Saving Time
    (also known as "Summer Time") and "leap" stuff.

    Tried many many other ways and anything that work with pure offsets is plain bad.
    Must work with proper tx names and pytz is the best way on Python.

    Offsets plainly don't work because DST-vs-no-DST varies based on specific locale.

    For example, US state of Arizona, while being part of `US/Mountain` time zone
    does NOT observe Daylight Saving Time, like rest of that time zone. As a result,
    it's effectively on US Mountain time zone in the winter and in US Pacific (right?)
    for most of rest of the year.

    Then, add to that the fact that Summer Time starts and ends on different dates
    depending on a country and, as a result, noon in San Diego, California is not
    guaranteed to be noon in Tijuana - a city only 30 kilometers *South*

    As a result of all the above, learned to specify timezone names as specifically
    as possible. Say, "America/Los_Angeles" vs "US/Pacific" and work only with
    time-zone-aware datetimes and only with timezones that are timezone-name aware
    and support something like Olson timezone DB (https://en.wikipedia.org/wiki/Tz_database)

    :param datetime.datetime dt:
        Some datetime object. May be timezone-naive, in which case origin timezone
        name is required and is used to localize the incoming dt before tz conversion.
    :param str destination_timezone_name:
        'UTC' or some standard tz name string like "America/Los_Angeles"
    :param str origin_timezone_name:
        'UTC' (default) or some standard tz name string like "Europe/Paris"
    :return:
    """


    if dt.tzinfo is None:
        assert origin_timezone_name
        origin_tz = Timezone(origin_timezone_name)
        # this step properly bakes together origin tz and dt
        tz_local_dt = origin_tz.localize(dt)
    elif dt.tzinfo == UTC or isinstance(dt.tzinfo, DstTzInfo):
        # this is an easy way out. These TZs properly react to
        # .normalize() method so no need to do anything with dt
        tz_local_dt = dt
    else:
        # We are here if tzinfo is set on dt,
        # but we don't know what the implementation is
        # (possibly some offset-based thing)
        # and, thus don't trust it to do the right thing
        # Hence, flipping it to UTC-based safe intermediate state
        # which does not have daylight saving time issues.
        tz_local_dt = dt.astimezone(UTC)

    destination_tz = Timezone(destination_timezone_name)

    # this step properly (with account for Daylight saving time) moves
    # dt to other timezone.
    return destination_tz.normalize(tz_local_dt)