Python datetime.tzinfo() Examples

The following are code examples for showing how to use datetime.tzinfo(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: bigquerylayers   Author: smandaric   File: reference.py    GNU General Public License v3.0 7 votes vote down vote up
def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self

        # Find first Sunday in April & the last in October.
        start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
        end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))

        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        if start <= dt.replace(tzinfo=None) < end:
            return HOUR
        else:
            return ZERO 
Example 2
Project: bigquerylayers   Author: smandaric   File: well_known_types_test.py    GNU General Public License v3.0 6 votes vote down vote up
def testDatetimeConversionWithTimezone(self):
    class TZ(datetime.tzinfo):

      def utcoffset(self, _):
        return datetime.timedelta(hours=1)

      def dst(self, _):
        return datetime.timedelta(0)

      def tzname(self, _):
        return 'UTC+1'

    message1 = timestamp_pb2.Timestamp()
    dt = datetime.datetime(1970, 1, 1, 1, tzinfo=TZ())
    message1.FromDatetime(dt)
    message2 = timestamp_pb2.Timestamp()
    dt = datetime.datetime(1970, 1, 1, 0)
    message2.FromDatetime(dt)
    self.assertEqual(message1, message2) 
Example 3
Project: bigquerylayers   Author: smandaric   File: types.py    GNU General Public License v3.0 6 votes vote down vote up
def TimeFromTicks(ticks, tz=None):
    """Construct a DB-API time value from the given ticks value.

    :type ticks: float
    :param ticks:
        a number of seconds since the epoch; see the documentation of the
        standard Python time module for details.

    :type tz: :class:`datetime.tzinfo`
    :param tz: (Optional) time zone to use for conversion

    :rtype: :class:`datetime.time`
    :returns: time represented by ticks.
    """
    dt = datetime.datetime.fromtimestamp(ticks, tz=tz)
    return dt.timetz() 
Example 4
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 6 votes vote down vote up
def _datetime_to_rfc3339(value, ignore_zone=True):
    """Convert a timestamp to a string.

    :type value: :class:`datetime.datetime`
    :param value: The datetime object to be converted to a string.

    :type ignore_zone: bool
    :param ignore_zone: If True, then the timezone (if any) of the datetime
                        object is ignored.

    :rtype: str
    :returns: The string representing the datetime stamp.
    """
    if not ignore_zone and value.tzinfo is not None:
        # Convert to UTC and remove the time zone info.
        value = value.replace(tzinfo=None) - value.utcoffset()

    return value.strftime(_RFC3339_MICROS) 
Example 5
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 6 votes vote down vote up
def is_ambiguous(self, dt):
        """
        Whether or not the "wall time" of a given datetime is ambiguous in this
        zone.

        :param dt:
            A :py:class:`datetime.datetime`, naive or time zone aware.


        :return:
            Returns ``True`` if ambiguous, ``False`` otherwise.

        .. versionadded:: 2.6.0
        """

        dt = dt.replace(tzinfo=self)

        wall_0 = enfold(dt, fold=0)
        wall_1 = enfold(dt, fold=1)

        same_offset = wall_0.utcoffset() == wall_1.utcoffset()
        same_dt = wall_0.replace(tzinfo=None) == wall_1.replace(tzinfo=None)

        return same_dt and not same_offset 
Example 6
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 6 votes vote down vote up
def _fold_status(self, dt_utc, dt_wall):
        """
        Determine the fold status of a "wall" datetime, given a representation
        of the same datetime as a (naive) UTC datetime. This is calculated based
        on the assumption that ``dt.utcoffset() - dt.dst()`` is constant for all
        datetimes, and that this offset is the actual number of hours separating
        ``dt_utc`` and ``dt_wall``.

        :param dt_utc:
            Representation of the datetime as UTC

        :param dt_wall:
            Representation of the datetime as "wall time". This parameter must
            either have a `fold` attribute or have a fold-naive
            :class:`datetime.tzinfo` attached, otherwise the calculation may
            fail.
        """
        if self.is_ambiguous(dt_wall):
            delta_wall = dt_wall - dt_utc
            _fold = int(delta_wall == (dt_utc.utcoffset() - dt_utc.dst()))
        else:
            _fold = 0

        return _fold 
Example 7
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 6 votes vote down vote up
def _isdst(self, dt):
        if not self.hasdst:
            return False
        elif dt is None:
            return None

        transitions = self.transitions(dt.year)

        if transitions is None:
            return False

        dt = dt.replace(tzinfo=None)

        isdst = self._naive_isdst(dt, transitions)

        # Handle ambiguous dates
        if not isdst and self.is_ambiguous(dt):
            return not self._fold(dt)
        else:
            return isdst 
Example 8
Project: openhatch   Author: campbe13   File: reference.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self

        # Find first Sunday in April & the last in October.
        start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
        end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))

        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        if start <= dt.replace(tzinfo=None) < end:
            return HOUR
        else:
            return ZERO 
Example 9
Project: SR-py-KMS-2018-11-16   Author: NN33NN   File: filetimes.py    The Unlicense 6 votes vote down vote up
def dt_to_filetime(dt):
        """Converts a datetime to Microsoft filetime format. If the object is
        time zone-naive, it is forced to UTC before conversion.

        >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0))
        '128930364000000000'

        >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
        '116444736000000000'

        >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0))
        '116444736000000000'
        
        >>> dt_to_filetime(datetime(2009, 7, 25, 23, 0, 0, 100))
        128930364000001000
        """
        if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None):
                dt = dt.replace(tzinfo=utc)
        ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS)
        return ft + (dt.microsecond * 10) 
Example 10
Project: SR-py-KMS-2018-11-16   Author: NN33NN   File: filetimes.py    The Unlicense 6 votes vote down vote up
def filetime_to_dt(ft):
        """Converts a Microsoft filetime number to a Python datetime. The new
        datetime object is time zone-naive but is equivalent to tzinfo=utc.

        >>> filetime_to_dt(116444736000000000)
        datetime.datetime(1970, 1, 1, 0, 0)

        >>> filetime_to_dt(128930364000000000)
        datetime.datetime(2009, 7, 25, 23, 0)
        
        >>> filetime_to_dt(128930364000001000)
        datetime.datetime(2009, 7, 25, 23, 0, 0, 100)
        """
        # Get seconds and remainder in terms of Unix epoch
        (s, ns100) = divmod(ft - EPOCH_AS_FILETIME, HUNDREDS_OF_NANOSECONDS)
        # Convert to datetime object
        dt = datetime.utcfromtimestamp(s)
        # Add remainder in as microseconds. Python 3.2 requires an integer
        dt = dt.replace(microsecond=(ns100 // 10))
        return dt 
Example 11
Project: SR-py-KMS-2018-11-16   Author: NN33NN   File: filetimes.py    The Unlicense 6 votes vote down vote up
def dt_to_filetime(dt):
        """Converts a datetime to Microsoft filetime format. If the object is
        time zone-naive, it is forced to UTC before conversion.

        >>> "%.0f" % dt_to_filetime(datetime(2009, 7, 25, 23, 0))
        '128930364000000000'

        >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0, tzinfo=utc))
        '116444736000000000'

        >>> "%.0f" % dt_to_filetime(datetime(1970, 1, 1, 0, 0))
        '116444736000000000'
        
        >>> dt_to_filetime(datetime(2009, 7, 25, 23, 0, 0, 100))
        128930364000001000
        """
        if (dt.tzinfo is None) or (dt.tzinfo.utcoffset(dt) is None):
                dt = dt.replace(tzinfo=utc)
        ft = EPOCH_AS_FILETIME + (timegm(dt.timetuple()) * HUNDREDS_OF_NANOSECONDS)
        return ft + (dt.microsecond * 10) 
Example 12
Project: SR-py-KMS-2018-11-16   Author: NN33NN   File: filetimes.py    The Unlicense 6 votes vote down vote up
def filetime_to_dt(ft):
        """Converts a Microsoft filetime number to a Python datetime. The new
        datetime object is time zone-naive but is equivalent to tzinfo=utc.

        >>> filetime_to_dt(116444736000000000)
        datetime.datetime(1970, 1, 1, 0, 0)

        >>> filetime_to_dt(128930364000000000)
        datetime.datetime(2009, 7, 25, 23, 0)
        
        >>> filetime_to_dt(128930364000001000)
        datetime.datetime(2009, 7, 25, 23, 0, 0, 100)
        """
        # Get seconds and remainder in terms of Unix epoch
        (s, ns100) = divmod(ft - EPOCH_AS_FILETIME, HUNDREDS_OF_NANOSECONDS)
        # Convert to datetime object
        dt = datetime.utcfromtimestamp(s)
        # Add remainder in as microseconds. Python 3.2 requires an integer
        dt = dt.replace(microsecond=(ns100 // 10))
        return dt 
Example 13
Project: razzy-spinner   Author: rafasashi   File: api.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, limit=20, upper_date_limit=None, lower_date_limit=None):
        """
        :param int limit: The number of data items to process in the current\
        round of processing.

        :param tuple upper_date_limit: The date at which to stop collecting\
        new data. This should be entered as a tuple which can serve as the\
        argument to `datetime.datetime`.\
        E.g. `date_limit=(2015, 4, 1, 12, 40)` for 12:30 pm on April 1 2015.

        :param tuple lower_date_limit: The date at which to stop collecting\
        new data. See `upper_data_limit` for formatting.
        """
        BasicTweetHandler.__init__(self, limit)

        self.upper_date_limit = None
        self.lower_date_limit = None
        if upper_date_limit:
            self.upper_date_limit = datetime(*upper_date_limit, tzinfo=LOCAL)
        if lower_date_limit:
            self.lower_date_limit = datetime(*lower_date_limit, tzinfo=LOCAL)

        self.startingup = True 
Example 14
Project: razzy-spinner   Author: rafasashi   File: api.py    GNU General Public License v3.0 6 votes vote down vote up
def check_date_limit(self, data, verbose=False):
        """
        Validate date limits.
        """
        if self.upper_date_limit or self.lower_date_limit:
            date_fmt = '%a %b %d %H:%M:%S +0000 %Y'
            tweet_date = \
                datetime.strptime(data['created_at'],
                                  date_fmt).replace(tzinfo=UTC)
            if (self.upper_date_limit and tweet_date > self.upper_date_limit) or \
               (self.lower_date_limit and tweet_date < self.lower_date_limit):
                if self.upper_date_limit:
                    message = "earlier"
                    date_limit = self.upper_date_limit
                else:
                    message = "later"
                    date_limit = self.lower_date_limit
                if verbose:
                    print("Date limit {0} is {1} than date of current tweet {2}".\
                      format(date_limit, message, tweet_date))
                self.do_stop = True 
Example 15
Project: misp42splunk   Author: remg427   File: base.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _mock(self, context=None):
        dt = datetime.datetime(
               year=random.randrange(600) + 1900,
               month=random.randrange(12) + 1,
               day=random.randrange(28) + 1,
               hour=random.randrange(24),
               minute=random.randrange(60),
               second=random.randrange(60),
               microsecond=random.randrange(1000000))

        if self.tzd == 'reject' or \
           self.drop_tzinfo or \
           self.tzd == 'allow' and random.randrange(2):
            return dt
        elif self.convert_tz:
            return dt.replace(tzinfo=self.UTC)
        else:
            return dt.replace(tzinfo=self.offset_timezone(hours=random.randrange(-12, 15),
                                                          minutes=random.choice([0, 30, 45]))) 
Example 16
Project: chattR   Author: patrickstocklin   File: tz.py    GNU General Public License v2.0 6 votes vote down vote up
def timezone_tag(parser, token):
    """
    Enables a given time zone just for this block.

    The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
    time zone name, or ``None``. If is it a time zone name, pytz is required.
    If it is ``None``, the default time zone is used within the block.

    Sample usage::

        {% timezone "Europe/Paris" %}
            It is {{ now }} in Paris.
        {% endtimezone %}

    """
    bits = token.split_contents()
    if len(bits) != 2:
        raise TemplateSyntaxError("'%s' takes one argument (timezone)" %
                                  bits[0])
    tz = parser.compile_filter(bits[1])
    nodelist = parser.parse(('endtimezone',))
    parser.delete_first_token()
    return TimezoneNode(nodelist, tz) 
Example 17
Project: asn1tools   Author: eerimoq   File: compat.py    MIT License 6 votes vote down vote up
def strptime(data, fmt):
        if fmt.endswith('%z'):
            date = datetime.strptime(data[:-5], fmt[:-2])

            try:
                sign = {'-': -1, '+': 1}[data[-5]]
                hours = sign * int(data[-4:-2])
                minutes = sign * int(data[-2:])
            except KeyError:
                raise ValueError(
                    "time data '{}' does not match format '{}'.".format(
                        data,
                        fmt))

            date = date.replace(tzinfo=timezone(timedelta(hours=hours,
                                                          minutes=minutes)))
        else:
            date = datetime.strptime(data, fmt)

        return date 
Example 18
Project: OpenBottle   Author: xiaozhuchacha   File: api.py    MIT License 6 votes vote down vote up
def __init__(self, limit=20, upper_date_limit=None, lower_date_limit=None):
        """
        :param int limit: The number of data items to process in the current\
        round of processing.

        :param tuple upper_date_limit: The date at which to stop collecting\
        new data. This should be entered as a tuple which can serve as the\
        argument to `datetime.datetime`.\
        E.g. `date_limit=(2015, 4, 1, 12, 40)` for 12:30 pm on April 1 2015.

        :param tuple lower_date_limit: The date at which to stop collecting\
        new data. See `upper_data_limit` for formatting.
        """
        BasicTweetHandler.__init__(self, limit)

        self.upper_date_limit = None
        self.lower_date_limit = None
        if upper_date_limit:
            self.upper_date_limit = datetime(*upper_date_limit, tzinfo=LOCAL)
        if lower_date_limit:
            self.lower_date_limit = datetime(*lower_date_limit, tzinfo=LOCAL)

        self.startingup = True 
Example 19
Project: OpenBottle   Author: xiaozhuchacha   File: api.py    MIT License 6 votes vote down vote up
def check_date_limit(self, data, verbose=False):
        """
        Validate date limits.
        """
        if self.upper_date_limit or self.lower_date_limit:
            date_fmt = '%a %b %d %H:%M:%S +0000 %Y'
            tweet_date = \
                datetime.strptime(data['created_at'],
                                  date_fmt).replace(tzinfo=UTC)
            if (self.upper_date_limit and tweet_date > self.upper_date_limit) or \
               (self.lower_date_limit and tweet_date < self.lower_date_limit):
                if self.upper_date_limit:
                    message = "earlier"
                    date_limit = self.upper_date_limit
                else:
                    message = "later"
                    date_limit = self.lower_date_limit
                if verbose:
                    print("Date limit {0} is {1} than date of current tweet {2}".\
                      format(date_limit, message, tweet_date))
                self.do_stop = True 
Example 20
Project: OpenBottle   Author: xiaozhuchacha   File: api.py    MIT License 6 votes vote down vote up
def __init__(self, limit=20, upper_date_limit=None, lower_date_limit=None):
        """
        :param int limit: The number of data items to process in the current\
        round of processing.

        :param tuple upper_date_limit: The date at which to stop collecting\
        new data. This should be entered as a tuple which can serve as the\
        argument to `datetime.datetime`.\
        E.g. `date_limit=(2015, 4, 1, 12, 40)` for 12:30 pm on April 1 2015.

        :param tuple lower_date_limit: The date at which to stop collecting\
        new data. See `upper_data_limit` for formatting.
        """
        BasicTweetHandler.__init__(self, limit)

        self.upper_date_limit = None
        self.lower_date_limit = None
        if upper_date_limit:
            self.upper_date_limit = datetime(*upper_date_limit, tzinfo=LOCAL)
        if lower_date_limit:
            self.lower_date_limit = datetime(*lower_date_limit, tzinfo=LOCAL)

        self.startingup = True 
Example 21
Project: OpenBottle   Author: xiaozhuchacha   File: api.py    MIT License 6 votes vote down vote up
def check_date_limit(self, data, verbose=False):
        """
        Validate date limits.
        """
        if self.upper_date_limit or self.lower_date_limit:
            date_fmt = '%a %b %d %H:%M:%S +0000 %Y'
            tweet_date = \
                datetime.strptime(data['created_at'],
                                  date_fmt).replace(tzinfo=UTC)
            if (self.upper_date_limit and tweet_date > self.upper_date_limit) or \
               (self.lower_date_limit and tweet_date < self.lower_date_limit):
                if self.upper_date_limit:
                    message = "earlier"
                    date_limit = self.upper_date_limit
                else:
                    message = "later"
                    date_limit = self.lower_date_limit
                if verbose:
                    print("Date limit {0} is {1} than date of current tweet {2}".\
                      format(date_limit, message, tweet_date))
                self.do_stop = True 
Example 22
Project: epg-dk.bundle   Author: ukdtom   File: reference.py    The Unlicense 6 votes vote down vote up
def dst(self, dt):
        if dt is None or dt.tzinfo is None:
            # An exception may be sensible here, in one or both cases.
            # It depends on how you want to treat them.  The default
            # fromutc() implementation (called by the default astimezone()
            # implementation) passes a datetime with dt.tzinfo is self.
            return ZERO
        assert dt.tzinfo is self

        # Find first Sunday in April & the last in October.
        start = first_sunday_on_or_after(DSTSTART.replace(year=dt.year))
        end = first_sunday_on_or_after(DSTEND.replace(year=dt.year))

        # Can't compare naive to aware objects, so strip the timezone from
        # dt first.
        if start <= dt.replace(tzinfo=None) < end:
            return HOUR
        else:
            return ZERO 
Example 23
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def time(self):
        """
        :return:
            A datetime.time object of the time
        """

        return time(self.hour, self.minute, self.second, self.microsecond, self.tzinfo) 
Example 24
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def utcoffset(self):
        """
        :return:
            None or a datetime.timedelta() of the offset from UTC
        """

        if self.tzinfo is None:
            return None
        return self.tzinfo.utcoffset(self.replace(year=2000)) 
Example 25
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def dst(self):
        """
        :return:
            None or a datetime.timedelta() of the daylight savings time offset
        """

        if self.tzinfo is None:
            return None
        return self.tzinfo.dst(self.replace(year=2000)) 
Example 26
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def tzname(self):
        """
        :return:
            None or the name of the timezone as a unicode string in Python 3
            and a byte string in Python 2
        """

        if self.tzinfo is None:
            return None
        return self.tzinfo.tzname(self.replace(year=2000)) 
Example 27
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        timestamp = ((dt.toordinal() - EPOCHORDINAL) * 86400
                     + dt.hour * 3600
                     + dt.minute * 60
                     + dt.second)
        return time.localtime(timestamp+time.timezone).tm_isdst 
Example 28
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt):
        if not self._start_delta:
            return False
        year = datetime.datetime(dt.year, 1, 1)
        start = year+self._start_delta
        end = year+self._end_delta
        dt = dt.replace(tzinfo=None)
        if start < end:
            return dt >= start and dt < end
        else:
            return dt >= start or dt < end 
Example 29
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _delta(self, x, isend=0):
        kwargs = {}
        if x.month is not None:
            kwargs["month"] = x.month
            if x.weekday is not None:
                kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week)
                if x.week > 0:
                    kwargs["day"] = 1
                else:
                    kwargs["day"] = 31
            elif x.day:
                kwargs["day"] = x.day
        elif x.yday is not None:
            kwargs["yearday"] = x.yday
        elif x.jyday is not None:
            kwargs["nlyearday"] = x.jyday
        if not kwargs:
            # Default is to start on first sunday of april, and end
            # on last sunday of october.
            if not isend:
                kwargs["month"] = 4
                kwargs["day"] = 1
                kwargs["weekday"] = relativedelta.SU(+1)
            else:
                kwargs["month"] = 10
                kwargs["day"] = 31
                kwargs["weekday"] = relativedelta.SU(-1)
        if x.time is not None:
            kwargs["seconds"] = x.time
        else:
            # Default is 2AM.
            kwargs["seconds"] = 7200
        if isend:
            # Convert to standard time, to follow the documented way
            # of working with the extra hour. See the documentation
            # of the tzinfo class.
            delta = self._dst_offset-self._std_offset
            kwargs["seconds"] -= delta.seconds+delta.days*86400
        return relativedelta.relativedelta(**kwargs) 
Example 30
Project: Splunk_CBER_App   Author: MHaggis   File: tz.py    MIT License 5 votes vote down vote up
def _find_comp(self, dt):
        if len(self._comps) == 1:
            return self._comps[0]
        dt = dt.replace(tzinfo=None)
        try:
            return self._cachecomp[self._cachedate.index(dt)]
        except ValueError:
            pass
        lastcomp = None
        lastcompdt = None
        for comp in self._comps:
            if not comp.isdst:
                # Handle the extra hour in DST -> STD
                compdt = comp.rrule.before(dt-comp.tzoffsetdiff, inc=True)
            else:
                compdt = comp.rrule.before(dt, inc=True)
            if compdt and (not lastcompdt or lastcompdt < compdt):
                lastcompdt = compdt
                lastcomp = comp
        if not lastcomp:
            # RFC says nothing about what to do when a given
            # time is before the first onset date. We'll look for the
            # first standard component, or the first component, if
            # none is found.
            for comp in self._comps:
                if not comp.isdst:
                    lastcomp = comp
                    break
            else:
                lastcomp = comp[0]
        self._cachedate.insert(0, dt)
        self._cachecomp.insert(0, lastcomp)
        if len(self._cachedate) > 10:
            self._cachedate.pop()
            self._cachecomp.pop()
        return lastcomp 
Example 31
Project: Splunk_CBER_App   Author: MHaggis   File: tzwin.py    MIT License 5 votes vote down vote up
def _isdst(self, dt):
        if not self._dstmonth:
            # dstmonth == 0 signals the zone has no daylight saving time
            return False
        dston = picknthweekday(dt.year, self._dstmonth, self._dstdayofweek,
                               self._dsthour, self._dstminute,
                               self._dstweeknumber)
        dstoff = picknthweekday(dt.year, self._stdmonth, self._stddayofweek,
                                self._stdhour, self._stdminute,
                                self._stdweeknumber)
        if dston < dstoff:
            return dston <= dt.replace(tzinfo=None) < dstoff
        else:
            return not dstoff <= dt.replace(tzinfo=None) < dston 
Example 32
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt) 
Example 33
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 34
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 35
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def _p(*args):
    """Factory function for unpickling pytz tzinfo instances.

    Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
    by shortening the path.
    """
    return unpickler(*args) 
Example 36
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 37
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 38
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _microseconds_from_datetime(value):
    """Convert non-none datetime to microseconds.

    :type value: :class:`datetime.datetime`
    :param value: The timestamp to convert.

    :rtype: int
    :returns: The timestamp, in microseconds.
    """
    if not value.tzinfo:
        value = value.replace(tzinfo=UTC)
    # Regardless of what timezone is on the value, convert it to UTC.
    value = value.astimezone(UTC)
    # Convert the datetime to a microsecond timestamp.
    return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond 
Example 39
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _rfc3339_to_datetime(dt_str):
    """Convert a microsecond-precision timestamp to a native datetime.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    """
    return datetime.datetime.strptime(dt_str, _RFC3339_MICROS).replace(tzinfo=UTC) 
Example 40
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _rfc3339_nanos_to_datetime(dt_str):
    """Convert a nanosecond-precision timestamp to a native datetime.

    .. note::

       Python datetimes do not support nanosecond precision;  this function
       therefore truncates such values to microseconds.

    :type dt_str: str
    :param dt_str: The string to convert.

    :rtype: :class:`datetime.datetime`
    :returns: The datetime object created from the string.
    :raises ValueError: If the timestamp does not match the RFC 3339
                        regular expression.
    """
    with_nanos = _RFC3339_NANOS.match(dt_str)
    if with_nanos is None:
        raise ValueError(
            "Timestamp: %r, does not match pattern: %r"
            % (dt_str, _RFC3339_NANOS.pattern)
        )
    bare_seconds = datetime.datetime.strptime(
        with_nanos.group("no_fraction"), _RFC3339_NO_FRACTION
    )
    fraction = with_nanos.group("nanos")
    if fraction is None:
        micros = 0
    else:
        scale = 9 - len(fraction)
        nanos = int(fraction) * (10 ** scale)
        micros = nanos // 1000
    return bare_seconds.replace(microsecond=micros, tzinfo=UTC) 
Example 41
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 5 votes vote down vote up
def enfold(dt, fold=1):
        """
        Provides a unified interface for assigning the ``fold`` attribute to
        datetimes both before and after the implementation of PEP-495.

        :param fold:
            The value for the ``fold`` attribute in the returned datetime. This
            should be either 0 or 1.

        :return:
            Returns an object for which ``getattr(dt, 'fold', 0)`` returns
            ``fold`` for all versions of Python. In versions prior to
            Python 3.6, this is a ``_DatetimeWithFold`` object, which is a
            subclass of :py:class:`datetime.datetime` with the ``fold``
            attribute added, if ``fold`` is 1.

        .. versionadded:: 2.6.0
        """
        if getattr(dt, 'fold', 0) == fold:
            return dt

        args = dt.timetuple()[:6]
        args += (dt.microsecond, dt.tzinfo)

        if fold:
            return _DatetimeWithFold(*args)
        else:
            return datetime(*args) 
Example 42
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 5 votes vote down vote up
def _validate_fromutc_inputs(f):
    """
    The CPython version of ``fromutc`` checks that the input is a ``datetime``
    object and that ``self`` is attached as its ``tzinfo``.
    """
    @wraps(f)
    def fromutc(self, dt):
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")
        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        return f(self, dt)

    return fromutc 
Example 43
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 5 votes vote down vote up
def fromutc(self, dt):
        """ Given a datetime in UTC, return local time """
        if not isinstance(dt, datetime):
            raise TypeError("fromutc() requires a datetime argument")

        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # Get transitions - if there are none, fixed offset
        transitions = self.transitions(dt.year)
        if transitions is None:
            return dt + self.utcoffset(dt)

        # Get the transition times in UTC
        dston, dstoff = transitions

        dston -= self._std_offset
        dstoff -= self._std_offset

        utc_transitions = (dston, dstoff)
        dt_utc = dt.replace(tzinfo=None)

        isdst = self._naive_isdst(dt_utc, utc_transitions)

        if isdst:
            dt_wall = dt + self._dst_offset
        else:
            dt_wall = dt + self._std_offset

        _fold = int(not isdst and self.is_ambiguous(dt_wall))

        return enfold(dt_wall, fold=_fold) 
Example 44
Project: AshsSDK   Author: thehappydinoa   File: _common.py    MIT License 5 votes vote down vote up
def _naive_isdst(self, dt, transitions):
        dston, dstoff = transitions

        dt = dt.replace(tzinfo=None)

        if dston < dstoff:
            isdst = dston <= dt < dstoff
        else:
            isdst = not dstoff <= dt < dston

        return isdst 
Example 45
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def _isdst(self, dt, fold_naive=True):
        # We can't use mktime here. It is unstable when deciding if
        # the hour near to a change is DST or not.
        #
        # timestamp = time.mktime((dt.year, dt.month, dt.day, dt.hour,
        #                         dt.minute, dt.second, dt.weekday(), 0, -1))
        # return time.localtime(timestamp).tm_isdst
        #
        # The code above yields the following result:
        #
        # >>> import tz, datetime
        # >>> t = tz.tzlocal()
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,16,0,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRST'
        # >>> datetime.datetime(2003,2,15,22,tzinfo=t).tzname()
        # 'BRDT'
        # >>> datetime.datetime(2003,2,15,23,tzinfo=t).tzname()
        # 'BRDT'
        #
        # Here is a more stable implementation:
        #
        if not self._hasdst:
            return False

        # Check for ambiguous times:
        dstval = self._naive_is_dst(dt)
        fold = getattr(dt, 'fold', None)

        if self.is_ambiguous(dt):
            if fold is not None:
                return not self._fold(dt)
            else:
                return True

        return dstval 
Example 46
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def fromutc(self, dt):
        """
        The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.

        :param dt:
            A :py:class:`datetime.datetime` object.

        :raises TypeError:
            Raised if ``dt`` is not a :py:class:`datetime.datetime` object.

        :raises ValueError:
            Raised if this is called with a ``dt`` which does not have this
            ``tzinfo`` attached.

        :return:
            Returns a :py:class:`datetime.datetime` object representing the
            wall time in ``self``'s time zone.
        """
        # These isinstance checks are in datetime.tzinfo, so we'll preserve
        # them, even if we don't care about duck typing.
        if not isinstance(dt, datetime.datetime):
            raise TypeError("fromutc() requires a datetime argument")

        if dt.tzinfo is not self:
            raise ValueError("dt.tzinfo is not self")

        # First treat UTC as wall time and get the transition we're in.
        idx = self._find_last_transition(dt, in_utc=True)
        tti = self._get_ttinfo(idx)

        dt_out = dt + datetime.timedelta(seconds=tti.offset)

        fold = self.is_ambiguous(dt_out, idx=idx)

        return enfold(dt_out, fold=int(fold)) 
Example 47
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def _delta(self, x, isend=0):
        from dateutil import relativedelta
        kwargs = {}
        if x.month is not None:
            kwargs["month"] = x.month
            if x.weekday is not None:
                kwargs["weekday"] = relativedelta.weekday(x.weekday, x.week)
                if x.week > 0:
                    kwargs["day"] = 1
                else:
                    kwargs["day"] = 31
            elif x.day:
                kwargs["day"] = x.day
        elif x.yday is not None:
            kwargs["yearday"] = x.yday
        elif x.jyday is not None:
            kwargs["nlyearday"] = x.jyday
        if not kwargs:
            # Default is to start on first sunday of april, and end
            # on last sunday of october.
            if not isend:
                kwargs["month"] = 4
                kwargs["day"] = 1
                kwargs["weekday"] = relativedelta.SU(+1)
            else:
                kwargs["month"] = 10
                kwargs["day"] = 31
                kwargs["weekday"] = relativedelta.SU(-1)
        if x.time is not None:
            kwargs["seconds"] = x.time
        else:
            # Default is 2AM.
            kwargs["seconds"] = 7200
        if isend:
            # Convert to standard time, to follow the documented way
            # of working with the extra hour. See the documentation
            # of the tzinfo class.
            delta = self._dst_offset - self._std_offset
            kwargs["seconds"] -= delta.seconds + delta.days * 86400
        return relativedelta.relativedelta(**kwargs) 
Example 48
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def get(self, tzid=None):
        """
        Retrieve a :py:class:`datetime.tzinfo` object by its ``tzid``.

        :param tzid:
            If there is exactly one time zone available, omitting ``tzid``
            or passing :py:const:`None` value returns it. Otherwise a valid
            key (which can be retrieved from :func:`keys`) is required.

        :raises ValueError:
            Raised if ``tzid`` is not specified but there are either more
            or fewer than 1 zone defined.

        :returns:
            Returns either a :py:class:`datetime.tzinfo` object representing
            the relevant time zone or :py:const:`None` if the ``tzid`` was
            not found.
        """
        if tzid is None:
            if len(self._vtz) == 0:
                raise ValueError("no timezones defined")
            elif len(self._vtz) > 1:
                raise ValueError("more than one timezone available")
            tzid = next(iter(self._vtz))

        return self._vtz.get(tzid) 
Example 49
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def datetime_exists(dt, tz=None):
    """
    Given a datetime and a time zone, determine whether or not a given datetime
    would fall in a gap.

    :param dt:
        A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
        is provided.)

    :param tz:
        A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
        ``None`` or not provided, the datetime's own time zone will be used.

    :return:
        Returns a boolean value whether or not the "wall time" exists in ``tz``.
    """
    if tz is None:
        if dt.tzinfo is None:
            raise ValueError('Datetime is naive and no time zone provided.')
        tz = dt.tzinfo

    dt = dt.replace(tzinfo=None)

    # This is essentially a test of whether or not the datetime can survive
    # a round trip to UTC.
    dt_rt = dt.replace(tzinfo=tz).astimezone(tzutc()).astimezone(tz)
    dt_rt = dt_rt.replace(tzinfo=None)

    return dt == dt_rt 
Example 50
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 5 votes vote down vote up
def _datetime_to_timestamp(dt):
    """
    Convert a :class:`datetime.datetime` object to an epoch timestamp in seconds
    since January 1, 1970, ignoring the time zone.
    """
    return _total_seconds((dt.replace(tzinfo=None) - EPOCH)) 
Example 51
Project: pytracts   Author: rmorlok   File: util.py    Apache License 2.0 5 votes vote down vote up
def datetime_to_ms(dt):
    if dt.tzinfo is None:
        time_zone_offset = 0
        local_epoch = datetime.datetime.utcfromtimestamp(0)
    else:
        time_zone_offset = dt.tzinfo.utcoffset(dt).total_seconds()
        # Determine Jan 1, 1970 local time.
        local_epoch = datetime.datetime.fromtimestamp(-time_zone_offset,
                                                      tz=dt.tzinfo)
    delta = dt - local_epoch

    return int(delta.total_seconds() * 1000) 
Example 52
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt) 
Example 53
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 54
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.replace(tzinfo=self) 
Example 55
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _p(*args):
    """Factory function for unpickling pytz tzinfo instances.

    Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
    by shortening the path.
    """
    return unpickler(*args) 
Example 56
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 57
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.replace(tzinfo=self) 
Example 58
Project: deb-python-cassandra-driver   Author: openstack   File: test_validation.py    Apache License 2.0 5 votes vote down vote up
def test_datetime_tzinfo_io(self):
        class TZ(tzinfo):
            def utcoffset(self, date_time):
                return timedelta(hours=-1)
            def dst(self, date_time):
                return None

        now = datetime(1982, 1, 1, tzinfo=TZ())
        dt = self.DatetimeTest.objects.create(test_id=1, created_at=now)
        dt2 = self.DatetimeTest.objects(test_id=1).first()
        self.assertEqual(dt2.created_at.timetuple()[:6], (now + timedelta(hours=1)).timetuple()[:6]) 
Example 59
Project: pyspark-cassandra   Author: TargetHolding   File: types.py    Apache License 2.0 5 votes vote down vote up
def _decode_primitives(ctype, cvalue):
    fmt = _numpy_to_struct_formats.get(ctype)

    # if unsupported, return as the list if bytes it was
    if not fmt:
        return cvalue

    primitives = _unpack(fmt, cvalue)

    if ctype == '>M8[ms]':
        return [datetime.utcfromtimestamp(l).replace(tzinfo=UTC) for l in primitives]
    else:
        return primitives 
Example 60
Project: Repobot   Author: Desgard   File: tz.py    MIT License 5 votes vote down vote up
def utc_aware(unaware):
    """decorator for adding UTC tzinfo to datetime's utcfoo methods"""
    def utc_method(*args, **kwargs):
        dt = unaware(*args, **kwargs)
        return dt.replace(tzinfo=UTC)
    return utc_method 
Example 61
Project: misp42splunk   Author: remg427   File: base.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_timestamp(self, value):
        try:
            return datetime.datetime(1970, 1, 1, tzinfo=self.UTC) + datetime.timedelta(seconds=value)
        except (ValueError, TypeError):
            return None 
Example 62
Project: misp42splunk   Author: remg427   File: base.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate_tz(self, value, context=None):
        if value.tzinfo is None:
            if not self.drop_tzinfo:
                if self.tzd == 'require':
                    raise ValidationError(self.messages['validate_tzd_require'])
                if self.tzd == 'utc':
                    raise ValidationError(self.messages['validate_utc_none'])
        else:
            if self.drop_tzinfo:
                raise ValidationError(self.messages['validate_tzd_reject'])
            if self.tzd == 'reject':
                raise ValidationError(self.messages['validate_tzd_reject'])
            if self.convert_tz \
              and value.tzinfo.utcoffset(value) != self.TIMEDELTA_ZERO:
                raise ValidationError(self.messages['validate_utc_wrong']) 
Example 63
Project: misp42splunk   Author: remg427   File: base.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def to_primitive(self, value, context=None):
        if value.tzinfo is None:
            value = value.replace(tzinfo=self.UTC)
        else:
            value = value.astimezone(self.UTC)
        delta = value - self.EPOCH
        ts = (delta.days * 24 * 3600) + delta.seconds + delta.microseconds / 1E6
        if delta.microseconds:
            return ts
        else:
            return int(ts) 
Example 64
Project: pinform   Author: sinarezaei   File: client.py    MIT License 5 votes vote down vote up
def load_points_as_dataframe(self, measurement: Type[T], tags: Optional[Dict[str, str]] = None,
                                 time_range: Union[datetime.date, Tuple[datetime.datetime, datetime.datetime]] = None,
                                 limit: Optional[int] = None, tz: datetime.tzinfo = pytz.utc) -> DataFrame:
        return MeasurementUtils.to_dataframe(self.load_points(measurement, tags, time_range, limit, tz)) 
Example 65
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def fromutc(self, dt):
        if dt.tzinfo is None:
            return self.localize(dt)
        return super(utc.__class__, self).fromutc(dt) 
Example 66
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 67
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 68
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def _p(*args):
    """Factory function for unpickling pytz tzinfo instances.

    Just a wrapper around tzinfo.unpickler to save a few bytes in each pickle
    by shortening the path.
    """
    return unpickler(*args) 
Example 69
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def localize(self, dt, is_dst=False):
        '''Convert naive time to local time'''
        if dt.tzinfo is not None:
            raise ValueError('Not naive datetime (tzinfo is already set)')
        return dt.replace(tzinfo=self) 
Example 70
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime'''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 71
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 4 votes vote down vote up
def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
        """
        :param year:
            The integer 0

        :param month:
            An integer from 1 to 12

        :param day:
            An integer from 1 to 31

        :param hour:
            An integer from 0 to 23

        :param minute:
            An integer from 0 to 59

        :param second:
            An integer from 0 to 59

        :param microsecond:
            An integer from 0 to 999999
        """

        if year != 0:
            raise ValueError('year must be 0')

        if month < 1 or month > 12:
            raise ValueError('month is out of range')

        if day < 0 or day > _DAYS_PER_MONTH_YEAR_0[month]:
            raise ValueError('day is out of range')

        if hour < 0 or hour > 23:
            raise ValueError('hour is out of range')

        if minute < 0 or minute > 59:
            raise ValueError('minute is out of range')

        if second < 0 or second > 59:
            raise ValueError('second is out of range')

        if microsecond < 0 or microsecond > 999999:
            raise ValueError('microsecond is out of range')

        self.year = year
        self.month = month
        self.day = day
        self.hour = hour
        self.minute = minute
        self.second = second
        self.microsecond = microsecond
        self.tzinfo = tzinfo 
Example 72
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 4 votes vote down vote up
def replace(self, year=None, month=None, day=None, hour=None, minute=None,
                second=None, microsecond=None, tzinfo=None):
        """
        Returns a new datetime.datetime or asn1crypto.util.extended_datetime
        object with the specified components replaced

        :return:
            A datetime.datetime or asn1crypto.util.extended_datetime object
        """

        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day
        if hour is None:
            hour = self.hour
        if minute is None:
            minute = self.minute
        if second is None:
            second = self.second
        if microsecond is None:
            microsecond = self.microsecond
        if tzinfo is None:
            tzinfo = self.tzinfo

        if year > 0:
            cls = datetime
        else:
            cls = extended_datetime

        return cls(
            year,
            month,
            day,
            hour,
            minute,
            second,
            microsecond,
            tzinfo
        ) 
Example 73
Project: bigquerylayers   Author: smandaric   File: __init__.py    GNU General Public License v3.0 4 votes vote down vote up
def timezone(zone):
    r''' Return a datetime.tzinfo implementation for the given timezone

    >>> from datetime import datetime, timedelta
    >>> utc = timezone('UTC')
    >>> eastern = timezone('US/Eastern')
    >>> eastern.zone
    'US/Eastern'
    >>> timezone(unicode('US/Eastern')) is eastern
    True
    >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
    >>> loc_dt = utc_dt.astimezone(eastern)
    >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
    >>> loc_dt.strftime(fmt)
    '2002-10-27 01:00:00 EST (-0500)'
    >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 00:50:00 EST (-0500)'
    >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:50:00 EDT (-0400)'
    >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:10:00 EST (-0500)'

    Raises UnknownTimeZoneError if passed an unknown zone.

    >>> try:
    ...     timezone('Asia/Shangri-La')
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    >>> try:
    ...     timezone(unicode('\N{TRADE MARK SIGN}'))
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    '''
    if zone is None:
        raise UnknownTimeZoneError(None)

    if zone.upper() == 'UTC':
        return utc

    try:
        zone = ascii(zone)
    except UnicodeEncodeError:
        # All valid timezones are ASCII
        raise UnknownTimeZoneError(zone)

    zone = _case_insensitive_zone_lookup(_unmunge_zone(zone))
    if zone not in _tzinfo_cache:
        if zone in all_timezones_set:  # noqa
            fp = open_resource(zone)
            try:
                _tzinfo_cache[zone] = build_tzinfo(zone, fp)
            finally:
                fp.close()
        else:
            raise UnknownTimeZoneError(zone)

    return _tzinfo_cache[zone] 
Example 74
Project: AshsSDK   Author: thehappydinoa   File: tz.py    MIT License 4 votes vote down vote up
def datetime_ambiguous(dt, tz=None):
    """
    Given a datetime and a time zone, determine whether or not a given datetime
    is ambiguous (i.e if there are two times differentiated only by their DST
    status).

    :param dt:
        A :class:`datetime.datetime` (whose time zone will be ignored if ``tz``
        is provided.)

    :param tz:
        A :class:`datetime.tzinfo` with support for the ``fold`` attribute. If
        ``None`` or not provided, the datetime's own time zone will be used.

    :return:
        Returns a boolean value whether or not the "wall time" is ambiguous in
        ``tz``.

    .. versionadded:: 2.6.0
    """
    if tz is None:
        if dt.tzinfo is None:
            raise ValueError('Datetime is naive and no time zone provided.')

        tz = dt.tzinfo

    # If a time zone defines its own "is_ambiguous" function, we'll use that.
    is_ambiguous_fn = getattr(tz, 'is_ambiguous', None)
    if is_ambiguous_fn is not None:
        try:
            return tz.is_ambiguous(dt)
        except:
            pass

    # If it doesn't come out and tell us it's ambiguous, we'll just check if
    # the fold attribute has any effect on this particular date and time.
    dt = dt.replace(tzinfo=tz)
    wall_0 = enfold(dt, fold=0)
    wall_1 = enfold(dt, fold=1)

    same_offset = wall_0.utcoffset() == wall_1.utcoffset()
    same_dst = wall_0.dst() == wall_1.dst()

    return not (same_offset and same_dst) 
Example 75
Project: pytracts   Author: rmorlok   File: util.py    Apache License 2.0 4 votes vote down vote up
def decode_datetime(encoded_datetime):
    """Decode a DateTimeField parameter from a string to a python datetime.

    Args:
      encoded_datetime: A string in RFC 3339 format.

    Returns:
      A datetime object with the date and time specified in encoded_datetime.

    Raises:
      ValueError: If the string is not in a recognized format.
    """
    # Check if the string includes a time zone offset.  Break out the
    # part that doesn't include time zone info.  Convert to uppercase
    # because all our comparisons should be case-insensitive.
    time_zone_match = _TIME_ZONE_RE.search(encoded_datetime)
    if time_zone_match:
        time_string = encoded_datetime[:time_zone_match.start(1)].upper()
    else:
        time_string = encoded_datetime.upper()

    if '.' in time_string:
        format_string = '%Y-%m-%dT%H:%M:%S.%f'
    else:
        format_string = '%Y-%m-%dT%H:%M:%S'

    decoded_datetime = datetime.datetime.strptime(time_string, format_string)

    if not time_zone_match:
        return decoded_datetime

    # Time zone info was included in the parameter.  Add a tzinfo
    # object to the datetime.  Datetimes can't be changed after they're
    # created, so we'll need to create a new one.
    if time_zone_match.group('z'):
        offset_minutes = 0
    else:
        sign = time_zone_match.group('sign')
        hours, minutes = [int(value) for value in
                          time_zone_match.group('hours', 'minutes')]
        offset_minutes = hours * 60 + minutes
        if sign == '-':
            offset_minutes *= -1

    return datetime.datetime(decoded_datetime.year,
                             decoded_datetime.month,
                             decoded_datetime.day,
                             decoded_datetime.hour,
                             decoded_datetime.minute,
                             decoded_datetime.second,
                             decoded_datetime.microsecond,
                             TimeZoneOffset(offset_minutes)) 
Example 76
Project: openhatch   Author: campbe13   File: __init__.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def timezone(zone):
    r''' Return a datetime.tzinfo implementation for the given timezone 

    >>> from datetime import datetime, timedelta
    >>> utc = timezone('UTC')
    >>> eastern = timezone('US/Eastern')
    >>> eastern.zone
    'US/Eastern'
    >>> timezone(unicode('US/Eastern')) is eastern
    True
    >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
    >>> loc_dt = utc_dt.astimezone(eastern)
    >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
    >>> loc_dt.strftime(fmt)
    '2002-10-27 01:00:00 EST (-0500)'
    >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 00:50:00 EST (-0500)'
    >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:50:00 EDT (-0400)'
    >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:10:00 EST (-0500)'

    Raises UnknownTimeZoneError if passed an unknown zone.

    >>> try:
    ...     timezone('Asia/Shangri-La')
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    >>> try:
    ...     timezone(unicode('\N{TRADE MARK SIGN}'))
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    '''
    if zone.upper() == 'UTC':
        return utc

    try:
        zone = ascii(zone)
    except UnicodeEncodeError:
        # All valid timezones are ASCII
        raise UnknownTimeZoneError(zone)

    zone = _unmunge_zone(zone)
    if zone not in _tzinfo_cache:
        if zone in all_timezones_set:
            fp = open_resource(zone)
            try:
                _tzinfo_cache[zone] = build_tzinfo(zone, fp)
            finally:
                fp.close()
        else:
            raise UnknownTimeZoneError(zone)

    return _tzinfo_cache[zone] 
Example 77
Project: deb-python-cassandra-driver   Author: openstack   File: test_queryset.py    Apache License 2.0 4 votes vote down vote up
def test_tzaware_datetime_support(self):
        """Test that using timezone aware datetime instances works with the
        MinTimeUUID/MaxTimeUUID functions.
        """
        pk = uuid4()
        midpoint_utc = datetime.utcnow().replace(tzinfo=TzOffset(0))
        midpoint_helsinki = midpoint_utc.astimezone(TzOffset(3))

        # Assert pre-condition that we have the same logical point in time
        assert midpoint_utc.utctimetuple() == midpoint_helsinki.utctimetuple()
        assert midpoint_utc.timetuple() != midpoint_helsinki.timetuple()

        TimeUUIDQueryModel.create(
            partition=pk,
            time=uuid_from_time(midpoint_utc - timedelta(minutes=1)),
            data='1')

        TimeUUIDQueryModel.create(
            partition=pk,
            time=uuid_from_time(midpoint_utc),
            data='2')

        TimeUUIDQueryModel.create(
            partition=pk,
            time=uuid_from_time(midpoint_utc + timedelta(minutes=1)),
            data='3')

        assert ['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter(
            TimeUUIDQueryModel.partition == pk,
            TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_utc))]

        assert ['1', '2'] == [o.data for o in TimeUUIDQueryModel.filter(
            TimeUUIDQueryModel.partition == pk,
            TimeUUIDQueryModel.time <= functions.MaxTimeUUID(midpoint_helsinki))]

        assert ['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter(
            TimeUUIDQueryModel.partition == pk,
            TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_utc))]

        assert ['2', '3'] == [o.data for o in TimeUUIDQueryModel.filter(
            TimeUUIDQueryModel.partition == pk,
            TimeUUIDQueryModel.time >= functions.MinTimeUUID(midpoint_helsinki))] 
Example 78
Project: misp42splunk   Author: remg427   File: base.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def to_native(self, value, context=None):

        if isinstance(value, datetime.datetime):
            if value.tzinfo is None:
                if not self.drop_tzinfo:
                    if self.tzd == 'require':
                        raise ConversionError(self.messages['tzd_require'].format(value))
                    if self.tzd == 'utc':
                        value = value.replace(tzinfo=self.UTC)
            else:
                if self.tzd == 'reject':
                    raise ConversionError(self.messages['tzd_reject'].format(value))
                if self.convert_tz:
                    value = value.astimezone(self.UTC)
                if self.drop_tzinfo:
                    value = value.replace(tzinfo=None)
            return value

        if self.formats:
            # Delegate to datetime.datetime.strptime() using provided format strings.
            for fmt in self.formats:
                try:
                    dt = datetime.datetime.strptime(value, fmt)
                    break
                except (ValueError, TypeError):
                    continue
            else:
                raise ConversionError(self.messages['parse_formats'].format(value, ", ".join(self.formats)))
        elif self.parser:
            # Delegate to external parser.
            try:
                dt = self.parser(value)
            except:
                raise ConversionError(self.messages['parse_external'].format(value))
        else:
            # Use built-in parser.
            try:
                value = float(value)
            except ValueError:
                dt = self.from_string(value)
            else:
                dt = self.from_timestamp(value)
            if not dt:
                raise ConversionError(self.messages['parse'].format(value))

        if dt.tzinfo is None:
            if self.tzd == 'require':
                raise ConversionError(self.messages['parse_tzd_require'].format(value))
            if self.tzd == 'utc' and not self.drop_tzinfo:
                dt = dt.replace(tzinfo=self.UTC)
        else:
            if self.tzd == 'reject':
                raise ConversionError(self.messages['parse_tzd_reject'].format(value))
            if self.convert_tz:
                dt = dt.astimezone(self.UTC)
            if self.drop_tzinfo:
                dt = dt.replace(tzinfo=None)

        return dt 
Example 79
Project: chattR   Author: patrickstocklin   File: tz.py    GNU General Public License v2.0 4 votes vote down vote up
def do_timezone(value, arg):
    """
    Converts a datetime to local time in a given time zone.

    The argument must be an instance of a tzinfo subclass or a time zone name.
    If it is a time zone name, pytz is required.

    Naive datetimes are assumed to be in local time in the default time zone.
    """
    if not isinstance(value, datetime):
        return ''

    # Obtain a timezone-aware datetime
    try:
        if timezone.is_naive(value):
            default_timezone = timezone.get_default_timezone()
            value = timezone.make_aware(value, default_timezone)
    # Filters must never raise exceptions, and pytz' exceptions inherit
    # Exception directly, not a specific subclass. So catch everything.
    except Exception:
        return ''

    # Obtain a tzinfo instance
    if isinstance(arg, tzinfo):
        tz = arg
    elif isinstance(arg, six.string_types) and pytz is not None:
        try:
            tz = pytz.timezone(arg)
        except pytz.UnknownTimeZoneError:
            return ''
    else:
        return ''

    result = timezone.localtime(value, tz)

    # HACK: the convert_to_local_time flag will prevent
    #       automatic conversion of the value to local time.
    result = datetimeobject(result.year, result.month, result.day,
                            result.hour, result.minute, result.second,
                            result.microsecond, result.tzinfo)
    result.convert_to_local_time = False
    return result


# Template tags 
Example 80
Project: epg-dk.bundle   Author: ukdtom   File: __init__.py    The Unlicense 4 votes vote down vote up
def timezone(zone):
    r''' Return a datetime.tzinfo implementation for the given timezone

    >>> from datetime import datetime, timedelta
    >>> utc = timezone('UTC')
    >>> eastern = timezone('US/Eastern')
    >>> eastern.zone
    'US/Eastern'
    >>> timezone(unicode('US/Eastern')) is eastern
    True
    >>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
    >>> loc_dt = utc_dt.astimezone(eastern)
    >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
    >>> loc_dt.strftime(fmt)
    '2002-10-27 01:00:00 EST (-0500)'
    >>> (loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 00:50:00 EST (-0500)'
    >>> eastern.normalize(loc_dt - timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:50:00 EDT (-0400)'
    >>> (loc_dt + timedelta(minutes=10)).strftime(fmt)
    '2002-10-27 01:10:00 EST (-0500)'

    Raises UnknownTimeZoneError if passed an unknown zone.

    >>> try:
    ...     timezone('Asia/Shangri-La')
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    >>> try:
    ...     timezone(unicode('\N{TRADE MARK SIGN}'))
    ... except UnknownTimeZoneError:
    ...     print('Unknown')
    Unknown

    '''
    if zone.upper() == 'UTC':
        return utc

    try:
        zone = ascii(zone)
    except UnicodeEncodeError:
        # All valid timezones are ASCII
        raise UnknownTimeZoneError(zone)

    zone = _unmunge_zone(zone)
    if zone not in _tzinfo_cache:
        if zone in all_timezones_set:
            fp = open_resource(zone)
            try:
                _tzinfo_cache[zone] = build_tzinfo(zone, fp)
            finally:
                fp.close()
        else:
            raise UnknownTimeZoneError(zone)

    return _tzinfo_cache[zone]