Example #1
0
def parse(s, dayfirst=True, yearfirst=True, naivemode=NAIVEMODE_UTC):
    """
    Parses a datetime string in it and returns a `Delorean` object.

    If a timezone is detected in the datetime string it will be
    normalized to UTC, and a Delorean object with that datetime and
    timezone will be returned.

    If a timezone is not detected, the resulting timezone (and return object)
    depends on the value of the naivemode argument:
        '{mode_utc}' -- UTC is assumed
        '{mode_raise}' -- An exception is raised
        '{mode_naive}' -- Returns a naive datetime object (NOT a `Delorean`).

    Note that in the case of naivemode=='{mode_naive}' a Delorean object is
    not returned. This is because Delorean objects should always be timezone
    aware.

    """

    if not naivemode in NAIVE_MODES:
        raise ValueError("Unknown naivemode value: '%s'" % naivemode)

    try:
        dt = capture(s, dayfirst=dayfirst, yearfirst=yearfirst)
    except:
        # raise a parsing error.
        raise ValueError("Unknown string format")
    if dt.tzinfo is None:
        if naivemode == NAIVEMODE_UTC:
            # assuming datetime object passed in is UTC
            do = Delorean(datetime=dt, timezone=UTC)
        elif naivemode == NAIVEMODE_RAISE:
            raise DeloreanInvalidDatetime("Unable to determine timezone info")
        elif naivemode == NAIVEMODE_NAIVE:
            do = dt  #note that we are *not* returning a Delorean here
    else:
        dt = utc.normalize(dt)
        # makeing dt naive so we can pass it to Delorean
        dt = dt.replace(tzinfo=None)
        # if parse string has tzinfo we return a normalized UTC
        # delorean object that represents the time.
        do = Delorean(datetime=dt, timezone=UTC)
    return do
def parse(s, dayfirst=True, yearfirst=True):
    """
    Parses a datetime string in it and returns a `Delorean` object.

    If a timezone is detected in the datetime string it will be
    normalized to UTC, and a Delorean object with that datetime and
    timezone will be returned.
    """
    try:
        # Cheap handle common US tz abreviations
        for abr, repl in tz_abr.iteritems():
            if abr in s:
                s = s.replace(abr, repl)
        target_timezone = None
        if ' to ' in s or ' in ' in s:
            for search in (' to ', ' in '):
                if s.find(search) > 0:
                    pos = s.rfind(search)
                    sstr = len(search)
            target_timezone = s[pos + sstr:].strip()
            s = s[:pos].strip()
        s = convert_tzs_offsets(s)
        dt = capture(s, dayfirst=dayfirst, yearfirst=yearfirst)
    except:
        # raise a parsing error.
        raise ValueError("Unknown string format")
    if dt.tzinfo is None:
        # assuming datetime object passed in is UTC
        do = Delorean(datetime=dt, timezone=UTC)
    else:
        dt = utc.normalize(dt)
        # makeing dt naive so we can pass it to Delorean
        dt = dt.replace(tzinfo=None)
        # if parse string has tzinfo we return a normalized UTC
        # delorean object that represents the time.
        do = Delorean(datetime=dt, timezone=UTC)
        if target_timezone:
            do.shift(target_timezone)
    return do
Example #3
0
def parse(s, dayfirst=True, yearfirst=True):
    """
    Parses a datetime string in it and returns a `Delorean` object.

    If a timezone is detected in the datetime string it will be
    normalized to UTC, and a Delorean object with that datetime and
    timezone will be returned.
    """
    try:
        dt = capture(s, dayfirst=dayfirst, yearfirst=yearfirst)
    except:
        # raise a parsing error.
        raise ValueError("Unknown string format")
    if dt.tzinfo is None:
        # assuming datetime object passed in is UTC
        do = Delorean(datetime=dt, timezone=UTC)
    else:
        dt = utc.normalize(dt)
        # makeing dt naive so we can pass it to Delorean
        dt = dt.replace(tzinfo=None)
        # if parse string has tzinfo we return a normalized UTC
        # delorean object that represents the time.
        do = Delorean(datetime=dt, timezone=UTC)
    return do
Example #4
0
def parse(s, dayfirst=True, yearfirst=True):
    """
    Parses a datetime string in it and returns a `Delorean` object.

    If a timezone is detected in the datetime string it will be
    normalized to UTC, and a Delorean object with that datetime and
    timezone will be returned.
    """
    try:
        dt = capture(s, dayfirst=dayfirst, yearfirst=yearfirst)
    except:
        # raise a parsing error.
        raise ValueError("Unknown string format")
    if dt.tzinfo is None:
        # assuming datetime object passed in is UTC
        do = Delorean(datetime=dt, timezone=UTC)
    else:
        dt = utc.normalize(dt)
        # makeing dt naive so we can pass it to Delorean
        dt = dt.replace(tzinfo=None)
        # if parse string has tzinfo we return a normalized UTC
        # delorean object that represents the time.
        do = Delorean(datetime=dt, timezone=UTC)
    return do
def parse(datetime_str, timezone=None, dayfirst=True, yearfirst=True):
    """
    Parses a datetime string and returns a `Delorean` object.

    :param datetime_str: The string to be interpreted into a `Delorean` object.
    :param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
        offsets passed as part of datetime_str will be ignored.
    :param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
        (True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
    :param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
        year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.

    .. testsetup::

        from delorean import Delorean
        from delorean import parse

    .. doctest::

        >>> parse('2015-01-01 00:01:02')
        Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')

    If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
    `pytz.FixedOffest` as it's timezone.

    .. doctest::

        >>> parse('2015-01-01 00:01:02 -0800')
        Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))

    If the timezone argument is supplied, the returned Delorean object will be in the timezone supplied. Any offsets in
    the datetime_str will be ignored.

    .. doctest::

        >>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
        Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')

    If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
    timezone will be returned.

    .. doctest::

        >>> parse('2015-01-01 00:01:02 PST')
        Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')

    However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
    time.

        >>> parse('2015-01-01 00:01:02 EST')
        Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')

    """
    dt = capture(datetime_str, dayfirst=dayfirst, yearfirst=yearfirst)

    if timezone:
        dt = dt.replace(tzinfo=None)
        do = Delorean(datetime=dt, timezone=timezone)
    elif dt.tzinfo is None:
        # assuming datetime object passed in is UTC
        do = Delorean(datetime=dt, timezone='UTC')
    elif isinstance(dt.tzinfo, tzoffset):
        utcoffset = dt.tzinfo.utcoffset(None)
        total_seconds = (
            (utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)

        tz = pytz.FixedOffset(total_seconds / 60)
        dt = dt.replace(tzinfo=None)
        do = Delorean(dt, timezone=tz)
    elif isinstance(dt.tzinfo, tzlocal):
        tz = get_localzone()
        dt = dt.replace(tzinfo=None)
        do = Delorean(dt, timezone=tz)
    else:
        dt = pytz.utc.normalize(dt)
        # making dt naive so we can pass it to Delorean
        dt = dt.replace(tzinfo=None)
        # if parse string has tzinfo we return a normalized UTC
        # delorean object that represents the time.
        do = Delorean(datetime=dt, timezone='UTC')

    return do