Python datetime.datetime.datetime() Examples

The following are code examples for showing how to use datetime.datetime.datetime(). 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: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 7 votes vote down vote up
def isoformat(self, sep='T'):
        """
        Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
        date and time portions

        :param set:
            A single character of the separator to place between the date and
            time

        :return:
            The formatted datetime as a unicode string in Python 3 and a byte
            string in Python 2
        """

        if self.microsecond == 0:
            return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
        return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_pickling_subclass(self):
        # Make sure we can pickle/unpickle an instance of a subclass.
        offset = timedelta(minutes=-300)
        orig = PicklableFixedOffset(offset, 'cookie')
        self.assertIsInstance(orig, tzinfo)
        self.assertTrue(type(orig) is PicklableFixedOffset)
        self.assertEqual(orig.utcoffset(None), offset)
        self.assertEqual(orig.tzname(None), 'cookie')
        for pickler, unpickler, proto in pickle_choices:
            green = pickler.dumps(orig, proto)
            derived = unpickler.loads(green)
            self.assertIsInstance(derived, tzinfo)
            self.assertTrue(type(derived) is PicklableFixedOffset)
            self.assertEqual(derived.utcoffset(None), offset)
            self.assertEqual(derived.tzname(None), 'cookie')

#############################################################################
# Base class for testing a particular aspect of timedelta, time, date and
# datetime comparisons. 
Example 3
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_backdoor_resistance(self):
        # For fast unpickling, the constructor accepts a pickle string.
        # This is a low-overhead backdoor.  A user can (by intent or
        # mistake) pass a string directly, which (if it's the right length)
        # will get treated like a pickle, and bypass the normal sanity
        # checks in the constructor.  This can create insane objects.
        # The constructor doesn't want to burn the time to validate all
        # fields, but does check the month field.  This stops, e.g.,
        # datetime.datetime('1995-03-25') from yielding an insane object.
        base = '1995-03-25'
        if not issubclass(self.theclass, datetime):
            base = base[:4]
        for month_byte in '9', chr(0), chr(13), '\xff':
            self.assertRaises(TypeError, self.theclass,
                                         base[:2] + month_byte + base[3:])
        for ord_byte in range(1, 13):
            # This shouldn't blow up because of the month byte alone.  If
            # the implementation changes to do more-careful checking, it may
            # blow up because other fields are insane.
            self.theclass(base[:2] + chr(ord_byte) + base[3:])

#############################################################################
# datetime tests 
Example 4
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_argument_passing(self):
        cls = self.theclass
        # A datetime passes itself on, a time passes None.
        class introspective(tzinfo):
            def tzname(self, dt):    return dt and "real" or "none"
            def utcoffset(self, dt):
                return timedelta(minutes = dt and 42 or -42)
            dst = utcoffset

        obj = cls(1, 2, 3, tzinfo=introspective())

        expected = cls is time and "none" or "real"
        self.assertEqual(obj.tzname(), expected)

        expected = timedelta(minutes=(cls is time and -42 or 42))
        self.assertEqual(obj.utcoffset(), expected)
        self.assertEqual(obj.dst(), expected) 
Example 5
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 6 votes vote down vote up
def list_items(self, trashed_before=None):
        """List items in trash bin.

        Trashed directories are not descended into."""

        if not self.items:
            self._read_info_files()

        if trashed_before:
            # Convert relative date string to datetime object
            trashed_before = date_string_to_datetime(trashed_before)

            for f in sorted(self.items, key=lambda i: i.date_trashed):
                if f.date_trashed < trashed_before:
                    print("{}: {}".format(f.date_trashed, f.original_path))
        else:
            # Print all items
            print("\n".join(str(i.original_path) for i in sorted(self.items, key=lambda i: i.original_path))) 
Example 6
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 6 votes vote down vote up
def _comparison_error(self, other):
        """
        Raises a TypeError about the other object not being suitable for
        comparison

        :param other:
            The object being compared to
        """

        raise TypeError(unwrap(
            '''
            An asn1crypto.util.extended_datetime object can only be compared to
            an asn1crypto.util.extended_datetime or datetime.datetime object,
            not %s
            ''',
            type_name(other)
        )) 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: core.py    MIT License 6 votes vote down vote up
def set(self, value):
        """
        Sets the value of the object

        :param value:
            A unicode string, a datetime.datetime object or an
            asn1crypto.util.extended_datetime object

        :raises:
            ValueError - when an invalid value is passed
        """

        if isinstance(value, (datetime, extended_datetime)):
            value = value.strftime('%Y%m%d%H%M%SZ')
            if _PY2:
                value = value.decode('ascii')

        AbstractString.set(self, value)
        # Set it to None and let the class take care of converting the next
        # time that .native is called
        self._native = None 
Example 8
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 9
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 10
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 11
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 6 votes vote down vote up
def __deserialize_datatime(self, string):
        """
        Deserializes string to datetime.

        The string should be in iso8601 datetime format.

        :param string: str.
        :return: datetime.
        """
        try:
            from dateutil.parser import parse
            return parse(string)
        except ImportError:
            return string
        except ValueError:
            raise ApiException(
                status=0,
                reason=(
                    "Failed to parse `{0}` into a datetime object"
                    .format(string)
                )
            ) 
Example 12
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 13
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 14
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 15
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 16
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 17
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 18
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 19
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
        """
        Helper to create a parse action for converting parsed datetime string to Python datetime.datetime

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})

        Example::
            dt_expr = pyparsing_common.iso8601_datetime.copy()
            dt_expr.setParseAction(pyparsing_common.convertToDatetime())
            print(dt_expr.parseString("1999-12-31T23:59:59.999"))
        prints::
            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt)
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 20
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_constants(self):
        import datetime
        self.assertEqual(datetime.MINYEAR, 1)
        self.assertEqual(datetime.MAXYEAR, 9999)

#############################################################################
# tzinfo tests 
Example 21
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_non_abstractness(self):
        # In order to allow subclasses to get pickled, the C implementation
        # wasn't able to get away with having __init__ raise
        # NotImplementedError.
        useless = tzinfo()
        dt = datetime.max
        self.assertRaises(NotImplementedError, useless.tzname, dt)
        self.assertRaises(NotImplementedError, useless.utcoffset, dt)
        self.assertRaises(NotImplementedError, useless.dst, dt) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_subclass_must_override(self):
        class NotEnough(tzinfo):
            def __init__(self, offset, name):
                self.__offset = offset
                self.__name = name
        self.assertTrue(issubclass(NotEnough, tzinfo))
        ne = NotEnough(3, "NotByALongShot")
        self.assertIsInstance(ne, tzinfo)

        dt = datetime.now()
        self.assertRaises(NotImplementedError, ne.tzname, dt)
        self.assertRaises(NotImplementedError, ne.utcoffset, dt)
        self.assertRaises(NotImplementedError, ne.dst, dt) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_normal(self):
        fo = FixedOffset(3, "Three")
        self.assertIsInstance(fo, tzinfo)
        for dt in datetime.now(), None:
            self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
            self.assertEqual(fo.tzname(dt), "Three")
            self.assertEqual(fo.dst(dt), timedelta(minutes=42)) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        for dt in (self.theclass(1, 2, 3),
                   self.theclass.today()):
            # Verify dt -> string -> date identity.
            s = repr(dt)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            dt2 = eval(s)
            self.assertEqual(dt, dt2)

            # Verify identity via reconstructing from pieces.
            dt2 = self.theclass(dt.year, dt.month, dt.day)
            self.assertEqual(dt, dt2) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mixed_compare(self):
        our = self.theclass(2000, 4, 5)
        self.assertRaises(TypeError, cmp, our, 1)
        self.assertRaises(TypeError, cmp, 1, our)

        class AnotherDateTimeClass(object):
            def __cmp__(self, other):
                # Return "equal" so calling this can't be confused with
                # compare-by-address (which never says "equal" for distinct
                # objects).
                return 0
            __hash__ = None # Silence Py3k warning

        # This still errors, because date and datetime comparison raise
        # TypeError instead of NotImplemented when they don't know what to
        # do, in order to stop comparison from falling back to the default
        # compare-by-address.
        their = AnotherDateTimeClass()
        self.assertRaises(TypeError, cmp, our, their)
        # Oops:  The next stab raises TypeError in the C implementation,
        # but not in the Python implementation of datetime.  The difference
        # is due to that the Python implementation defines __cmp__ but
        # the C implementation defines tp_richcompare.  This is more pain
        # to fix than it's worth, so commenting out the test.
        # self.assertEqual(cmp(their, our), 0)

        # But date and datetime comparison return NotImplemented instead if the
        # other object has a timetuple attr.  This gives the other object a
        # chance to do the comparison.
        class Comparable(AnotherDateTimeClass):
            def timetuple(self):
                return ()

        their = Comparable()
        self.assertEqual(cmp(our, their), 0)
        self.assertEqual(cmp(their, our), 0)
        self.assertTrue(our == their)
        self.assertTrue(their == our) 
Example 26
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        for dt in (self.theclass(1, 2, 3, 4, 5, 6, 7),
                   self.theclass.now()):
            # Verify dt -> string -> datetime identity.
            s = repr(dt)
            self.assertTrue(s.startswith('datetime.'))
            s = s[9:]
            dt2 = eval(s)
            self.assertEqual(dt, dt2)

            # Verify identity via reconstructing from pieces.
            dt2 = self.theclass(dt.year, dt.month, dt.day,
                                dt.hour, dt.minute, dt.second,
                                dt.microsecond)
            self.assertEqual(dt, dt2) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_roundtrip(self):
        t = self.theclass(1, 2, 3, 4)

        # Verify t -> string -> time identity.
        s = repr(t)
        self.assertTrue(s.startswith('datetime.'))
        s = s[9:]
        t2 = eval(s)
        self.assertEqual(t, t2)

        # Verify identity via reconstructing from pieces.
        t2 = self.theclass(t.hour, t.minute, t.second,
                           t.microsecond)
        self.assertEqual(t, t2) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        name = 'datetime.' + self.theclass.__name__
        self.assertEqual(repr(self.theclass(1, 2, 3, 4)),
                         "%s(1, 2, 3, 4)" % name)
        self.assertEqual(repr(self.theclass(10, 2, 3, 4000)),
                         "%s(10, 2, 3, 4000)" % name)
        self.assertEqual(repr(self.theclass(0, 2, 3, 400000)),
                         "%s(0, 2, 3, 400000)" % name)
        self.assertEqual(repr(self.theclass(12, 2, 3, 0)),
                         "%s(12, 2, 3)" % name)
        self.assertEqual(repr(self.theclass(23, 15, 0, 0)),
                         "%s(23, 15)" % name) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_backdoor_resistance(self):
        # see TestDate.test_backdoor_resistance().
        base = '2:59.0'
        for hour_byte in ' ', '9', chr(24), '\xff':
            self.assertRaises(TypeError, self.theclass,
                                         hour_byte + base[1:])

# A mixin for classes with a tzinfo= argument.  Subclasses must define
# theclass as a class atribute, and theclass(1, 1, 1, tzinfo=whatever)
# must be legit (which is true for time and datetime). 
Example 30
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_utc_offset_out_of_bounds(self):
        class Edgy(tzinfo):
            def __init__(self, offset):
                self.offset = timedelta(minutes=offset)
            def utcoffset(self, dt):
                return self.offset

        cls = self.theclass
        for offset, legit in ((-1440, False),
                              (-1439, True),
                              (1439, True),
                              (1440, False)):
            if cls is time:
                t = cls(1, 2, 3, tzinfo=Edgy(offset))
            elif cls is datetime:
                t = cls(6, 6, 6, 1, 2, 3, tzinfo=Edgy(offset))
            else:
                assert 0, "impossible"
            if legit:
                aofs = abs(offset)
                h, m = divmod(aofs, 60)
                tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m)
                if isinstance(t, datetime):
                    t = t.timetz()
                self.assertEqual(str(t), "01:02:03" + tag)
            else:
                self.assertRaises(ValueError, str, t) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_extreme_hashes(self):
        # If an attempt is made to hash these via subtracting the offset
        # then hashing a datetime object, OverflowError results.  The
        # Python implementation used to blow up here.
        t = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, ""))
        hash(t)
        t = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
                          tzinfo=FixedOffset(-1439, ""))
        hash(t)

        # OTOH, an OOB offset should blow up.
        t = self.theclass(5, 5, 5, tzinfo=FixedOffset(-1440, ""))
        self.assertRaises(ValueError, hash, t) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_zones(self):
        est = FixedOffset(-300, "EST")
        utc = FixedOffset(0, "UTC")
        met = FixedOffset(60, "MET")
        t1 = datetime(2002, 3, 19,  7, 47, tzinfo=est)
        t2 = datetime(2002, 3, 19, 12, 47, tzinfo=utc)
        t3 = datetime(2002, 3, 19, 13, 47, tzinfo=met)
        self.assertEqual(t1.tzinfo, est)
        self.assertEqual(t2.tzinfo, utc)
        self.assertEqual(t3.tzinfo, met)
        self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
        self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
        self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
        self.assertEqual(t1.tzname(), "EST")
        self.assertEqual(t2.tzname(), "UTC")
        self.assertEqual(t3.tzname(), "MET")
        self.assertEqual(hash(t1), hash(t2))
        self.assertEqual(hash(t1), hash(t3))
        self.assertEqual(hash(t2), hash(t3))
        self.assertEqual(t1, t2)
        self.assertEqual(t1, t3)
        self.assertEqual(t2, t3)
        self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00")
        self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00")
        self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00")
        d = 'datetime.datetime(2002, 3, 19, '
        self.assertEqual(repr(t1), d + "7, 47, tzinfo=est)")
        self.assertEqual(repr(t2), d + "12, 47, tzinfo=utc)")
        self.assertEqual(repr(t3), d + "13, 47, tzinfo=met)") 
Example 33
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_combine(self):
        met = FixedOffset(60, "MET")
        d = date(2002, 3, 4)
        tz = time(18, 45, 3, 1234, tzinfo=met)
        dt = datetime.combine(d, tz)
        self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234,
                                        tzinfo=met)) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_now(self):
        meth = self.theclass.now
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth()
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(off42)
        again = meth(tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, 16)
        self.assertRaises(TypeError, meth, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, off42, off42)

        # We don't know which time zone we're in, and don't have a tzinfo
        # class to represent it, so seeing whether a tz argument actually
        # does a conversion is tricky.
        weirdtz = FixedOffset(timedelta(hours=15, minutes=58), "weirdtz", 0)
        utc = FixedOffset(0, "utc", 0)
        for dummy in range(3):
            now = datetime.now(weirdtz)
            self.assertIs(now.tzinfo, weirdtz)
            utcnow = datetime.utcnow().replace(tzinfo=utc)
            now2 = utcnow.astimezone(weirdtz)
            if abs(now - now2) < timedelta(seconds=30):
                break
            # Else the code is broken, or more than 30 seconds passed between
            # calls; assuming the latter, just try again.
        else:
            # Three strikes and we're out.
            self.fail("utcnow(), now(tz), or astimezone() may be broken") 
Example 35
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_timetuple(self):
        # TestDateTime tested most of this.  datetime adds a twist to the
        # DST flag.
        class DST(tzinfo):
            def __init__(self, dstvalue):
                if isinstance(dstvalue, int):
                    dstvalue = timedelta(minutes=dstvalue)
                self.dstvalue = dstvalue
            def dst(self, dt):
                return self.dstvalue

        cls = self.theclass
        for dstvalue, flag in (-33, 1), (33, 1), (0, 0), (None, -1):
            d = cls(1, 1, 1, 10, 20, 30, 40, tzinfo=DST(dstvalue))
            t = d.timetuple()
            self.assertEqual(1, t.tm_year)
            self.assertEqual(1, t.tm_mon)
            self.assertEqual(1, t.tm_mday)
            self.assertEqual(10, t.tm_hour)
            self.assertEqual(20, t.tm_min)
            self.assertEqual(30, t.tm_sec)
            self.assertEqual(0, t.tm_wday)
            self.assertEqual(1, t.tm_yday)
            self.assertEqual(flag, t.tm_isdst)

        # dst() returns wrong type.
        self.assertRaises(TypeError, cls(1, 1, 1, tzinfo=DST("x")).timetuple)

        # dst() at the edge.
        self.assertEqual(cls(1,1,1, tzinfo=DST(1439)).timetuple().tm_isdst, 1)
        self.assertEqual(cls(1,1,1, tzinfo=DST(-1439)).timetuple().tm_isdst, 1)

        # dst() out of range.
        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(1440)).timetuple)
        self.assertRaises(ValueError, cls(1,1,1, tzinfo=DST(-1440)).timetuple) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mixed_compare(self):
        t1 = datetime(1, 2, 3, 4, 5, 6, 7)
        t2 = datetime(1, 2, 3, 4, 5, 6, 7)
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=None)
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=FixedOffset(None, ""))
        self.assertEqual(t1, t2)
        t2 = t2.replace(tzinfo=FixedOffset(0, ""))
        self.assertRaises(TypeError, lambda: t1 == t2)

        # In datetime w/ identical tzinfo objects, utcoffset is ignored.
        class Varies(tzinfo):
            def __init__(self):
                self.offset = timedelta(minutes=22)
            def utcoffset(self, t):
                self.offset += timedelta(minutes=1)
                return self.offset

        v = Varies()
        t1 = t2.replace(tzinfo=v)
        t2 = t2.replace(tzinfo=v)
        self.assertEqual(t1.utcoffset(), timedelta(minutes=23))
        self.assertEqual(t2.utcoffset(), timedelta(minutes=24))
        self.assertEqual(t1, t2)

        # But if they're not identical, it isn't ignored.
        t2 = t2.replace(tzinfo=Varies())
        self.assertTrue(t1 < t2)  # t1's offset counter still going up 
Example 37
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bug_1028306(self):
        # Trying to compare a date to a datetime should act like a mixed-
        # type comparison, despite that datetime is a subclass of date.
        as_date = date.today()
        as_datetime = datetime.combine(as_date, time())
        self.assertTrue(as_date != as_datetime)
        self.assertTrue(as_datetime != as_date)
        self.assertFalse(as_date == as_datetime)
        self.assertFalse(as_datetime == as_date)
        self.assertRaises(TypeError, lambda: as_date < as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime < as_date)
        self.assertRaises(TypeError, lambda: as_date <= as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime <= as_date)
        self.assertRaises(TypeError, lambda: as_date > as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime > as_date)
        self.assertRaises(TypeError, lambda: as_date >= as_datetime)
        self.assertRaises(TypeError, lambda: as_datetime >= as_date)

        # Neverthelss, comparison should work with the base-class (date)
        # projection if use of a date method is forced.
        self.assertTrue(as_date.__eq__(as_datetime))
        different_day = (as_date.day + 1) % 20 + 1
        self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day)))

        # And date should compare with other subclasses of date.  If a
        # subclass wants to stop this, it's up to the subclass to do so.
        date_sc = SubclassDate(as_date.year, as_date.month, as_date.day)
        self.assertEqual(as_date, date_sc)
        self.assertEqual(date_sc, as_date)

        # Ditto for datetimes.
        datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month,
                                       as_date.day, 0, 0, 0)
        self.assertEqual(as_datetime, datetime_sc)
        self.assertEqual(datetime_sc, as_datetime) 
Example 38
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def parse_date(value):
    """Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    """
    if value:
        t = parsedate_tz(value.strip())
        if t is not None:
            try:
                year = t[0]
                # unfortunately that function does not tell us if two digit
                # years were part of the string, or if they were prefixed
                # with two zeroes.  So what we do is to assume that 69-99
                # refer to 1900, and everything below to 2000
                if year >= 0 and year <= 68:
                    year += 2000
                elif year >= 69 and year <= 99:
                    year += 1900
                return datetime(*((year,) + t[1:7])) - \
                       timedelta(seconds=t[-1] or 0)
            except (ValueError, OverflowError):
                return None 
Example 39
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 40
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def cookie_date(expires=None):
    """Formats the time to ensure compatibility with Netscape's cookie
    standard.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.

    :param expires: If provided that date is used, otherwise the current.
    """
    return _dump_date(expires, '-') 
Example 41
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def http_date(timestamp=None):
    """Formats the time to match the RFC1123 date format.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

    :param timestamp: If provided that date is used, otherwise the current.
    """
    return _dump_date(timestamp, ' ') 
Example 42
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: atom.py    Apache License 2.0 5 votes vote down vote up
def format_iso8601(obj):
    """Format a datetime object for iso8601"""
    iso8601 = obj.isoformat()
    if obj.tzinfo:
        return iso8601
    return iso8601 + 'Z' 
Example 43
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def timestamp_to_datetime(self, ts):
        """Used to convert the timestamp from `get_timestamp` into a
        datetime object.
        """
        return datetime.utcfromtimestamp(ts + EPOCH) 
Example 44
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def get_issue_date(self, header):
        rv = header.get('iat')
        if isinstance(rv, number_types):
            return datetime.utcfromtimestamp(int(rv)) 
Example 45
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def parse_date(value):
    """Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    """
    if value:
        t = parsedate_tz(value.strip())
        if t is not None:
            try:
                year = t[0]
                # unfortunately that function does not tell us if two digit
                # years were part of the string, or if they were prefixed
                # with two zeroes.  So what we do is to assume that 69-99
                # refer to 1900, and everything below to 2000
                if year >= 0 and year <= 68:
                    year += 2000
                elif year >= 69 and year <= 99:
                    year += 1900
                return datetime(*((year,) + t[1:7])) - \
                       timedelta(seconds=t[-1] or 0)
            except (ValueError, OverflowError):
                return None 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 47
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def http_date(timestamp=None):
    """Formats the time to match the RFC1123 date format.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

    :param timestamp: If provided that date is used, otherwise the current.
    """
    return _dump_date(timestamp, ' ') 
Example 48
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: atom.py    Apache License 2.0 5 votes vote down vote up
def format_iso8601(obj):
    """Format a datetime object for iso8601"""
    iso8601 = obj.isoformat()
    if obj.tzinfo:
        return iso8601
    return iso8601 + 'Z' 
Example 49
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 5 votes vote down vote up
def timestamp_to_datetime(self, ts):
        """Used to convert the timestamp from `get_timestamp` into a
        datetime object.
        """
        return datetime.utcfromtimestamp(ts + EPOCH) 
Example 50
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path=None, bin=None, info_file=None):
        self.bin = bin if bin else TrashBin()

        self.info_file = None
        self.original_path = None
        self.trashed = False
        self.trashed_path = None

        # TODO: Check FreeDesktop.org specs to see if timezone/UTC is specified.
        self.date_trashed = None  # datetime object in UTC

        if path:
            self.original_path = Path(path)

            # Get absolute path
            if not self.original_path.is_absolute():
                # Prepend current directory
                self.original_path = os.getcwd() / self.original_path

        if info_file:
            # Probably already a trashed file
            if isinstance(info_file, str):
                self.info_file = Path(info_file)
            elif isinstance(info_file, Path):
                self.info_file = info_file

            try:
                self._read_trashinfo_file()
            except Exception as e:
                raise Exception('Unable to read .trashinfo file ("%s"): %s', e, self.info_file) 
Example 51
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 5 votes vote down vote up
def _read_trashinfo_file(self, check_orphan=False):
        """Read .trashinfo file and set item attributes."""

        parser = CaseConfigParser(interpolation=None)

        try:
            # Read file and load attributes
            parser.read(str(self.info_file))
            trashinfo = parser[TRASHINFO_SECTION_HEADER]

            self.original_path = Path(trashinfo['Path'])
            self.trashed_path = self.bin.files_path / self.info_file.stem
            self.date_trashed = datetime.strptime(trashinfo['DeletionDate'], TRASHINFO_DATE_FORMAT)

        except Exception as e:
            # TODO: Should this be an error or a warning?
            log.warning('.trashinfo file appears invalid or empty (%s): %s', e, self.info_file)
            raise e

        else:
            log.debug("Read .trashinfo file: %s", self.info_file)

            if check_orphan:
                if self.trashed_path.exists():
                    # Underlying file exists in trash
                    self.trashed = True

                    log.debug("Underlying file confirmed: %s", self.trashed_path)
                else:
                    # Orphan .trashinfo file
                    raise OrphanTrashinfoFile("Underlying file \"%s\" not found for: %s", self.trashed_path, self.info_file) 
Example 52
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 5 votes vote down vote up
def date_string_to_datetime(s):
    "Convert date string to a datetime object using parsedatetime.Calendar()."

    # It's a shame that such a great library like parsedatetime
    # didn't go the extra inch and provide a decent API to get a
    # datetime object out of it.
    return datetime.fromtimestamp(mktime(parsedatetime.Calendar().parse(s)[0]))

# * Setup Click 
Example 53
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def replace(self, year=None, month=None, day=None):
        """
        Returns a new datetime.date or asn1crypto.util.extended_date
        object with the specified components replaced

        :return:
            A datetime.date or asn1crypto.util.extended_date object
        """

        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day

        if year > 0:
            cls = date
        else:
            cls = extended_date

        return cls(
            year,
            month,
            day
        ) 
Example 54
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def _comparison_error(self, other):
        raise TypeError(unwrap(
            '''
            An asn1crypto.util.extended_date object can only be compared to
            an asn1crypto.util.extended_date or datetime.date object, not %s
            ''',
            type_name(other)
        )) 
Example 55
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 56
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 57
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 58
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        so = self.utcoffset()
        oo = other.utcoffset()

        if (so is not None and oo is None) or (so is None and oo is not None):
            raise TypeError("can't compare offset-naive and offset-aware datetimes")

        if isinstance(other, datetime):
            return -1

        if not isinstance(other, self.__class__):
            self._comparison_error(other)

        st = (
            self.year,
            self.month,
            self.day,
            self.hour,
            self.minute,
            self.second,
            self.microsecond,
            so
        )
        ot = (
            other.year,
            other.month,
            other.day,
            other.hour,
            other.minute,
            other.second,
            other.microsecond,
            oo
        )

        if st < ot:
            return -1
        if st > ot:
            return 1
        return 0 
Example 59
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: core.py    MIT License 5 votes vote down vote up
def native(self):
        """
        The a native Python datatype representation of this value

        :return:
            A datetime.datetime object in the UTC timezone or None
        """

        if self.contents is None:
            return None

        if self._native is None:
            string = str_cls(self)
            has_timezone = re.search('[-\\+]', string)

            # We don't know what timezone it is in, or it is UTC because of a Z
            # suffix, so we just assume UTC
            if not has_timezone:
                string = string.rstrip('Z')
                date = self._date_by_len(string)
                self._native = date.replace(tzinfo=timezone.utc)

            else:
                # Python 2 doesn't support the %z format code, so we have to manually
                # process the timezone offset.
                date = self._date_by_len(string[0:-5])

                hours = int(string[-4:-2])
                minutes = int(string[-2:])
                delta = timedelta(hours=abs(hours), minutes=minutes)
                if hours < 0:
                    date -= delta
                else:
                    date += delta

                self._native = date.replace(tzinfo=timezone.utc)

        return self._native 
Example 60
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: core.py    MIT License 5 votes vote down vote up
def _date_by_len(self, string):
        """
        Parses a date from a string based on its length

        :param string:
            A unicode string to parse

        :return:
            A datetime.datetime object or a unicode string
        """

        strlen = len(string)

        year_num = int(string[0:2])
        if year_num < 50:
            prefix = '20'
        else:
            prefix = '19'

        if strlen == 10:
            return datetime.strptime(prefix + string, '%Y%m%d%H%M')

        if strlen == 12:
            return datetime.strptime(prefix + string, '%Y%m%d%H%M%S')

        return string 
Example 61
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: core.py    MIT License 5 votes vote down vote up
def _date_by_len(self, string):
        """
        Parses a date from a string based on its length

        :param string:
            A unicode string to parse

        :return:
            A datetime.datetime object, asn1crypto.util.extended_datetime object or
            a unicode string
        """

        strlen = len(string)

        date_format = None
        if strlen == 10:
            date_format = '%Y%m%d%H'
        elif strlen == 12:
            date_format = '%Y%m%d%H%M'
        elif strlen == 14:
            date_format = '%Y%m%d%H%M%S'
        elif strlen == 18:
            date_format = '%Y%m%d%H%M%S.%f'

        if date_format:
            if len(string) >= 4 and string[0:4] == '0000':
                # Year 2000 shares a calendar with year 0, and is supported natively
                t = datetime.strptime('2000' + string[4:], date_format)
                return extended_datetime(
                    0,
                    t.month,
                    t.day,
                    t.hour,
                    t.minute,
                    t.second,
                    t.microsecond,
                    t.tzinfo
                )
            return datetime.strptime(string, date_format)

        return string 
Example 62
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 5 votes vote down vote up
def __deserialize(self, data, klass):
        """
        Deserializes dict, list, str into an object.

        :param data: dict, list or str.
        :param klass: class literal, or string of class name.

        :return: object.
        """
        if data is None:
            return None

        if type(klass) == str:
            if klass.startswith('list['):
                sub_kls = re.match('list\[(.*)\]', klass).group(1)
                return [self.__deserialize(sub_data, sub_kls)
                        for sub_data in data]

            if klass.startswith('dict('):
                sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2)
                return {k: self.__deserialize(v, sub_kls)
                        for k, v in iteritems(data)}

            # convert str to class
            if klass in self.NATIVE_TYPES_MAPPING:
                klass = self.NATIVE_TYPES_MAPPING[klass]
            else:
                klass = getattr(models, klass)

        if klass in self.PRIMITIVE_TYPES:
            return self.__deserialize_primitive(data, klass)
        elif klass == object:
            return self.__deserialize_object(data)
        elif klass == date:
            return self.__deserialize_date(data)
        elif klass == datetime:
            return self.__deserialize_datatime(data)
        else:
            return self.__deserialize_model(data, klass) 
Example 63
Project: flasky   Author: RoseOu   File: http.py    MIT License 5 votes vote down vote up
def parse_date(value):
    """Parse one of the following date formats into a datetime object:

    .. sourcecode:: text

        Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
        Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
        Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

    If parsing fails the return value is `None`.

    :param value: a string with a supported date format.
    :return: a :class:`datetime.datetime` object.
    """
    if value:
        t = parsedate_tz(value.strip())
        if t is not None:
            try:
                year = t[0]
                # unfortunately that function does not tell us if two digit
                # years were part of the string, or if they were prefixed
                # with two zeroes.  So what we do is to assume that 69-99
                # refer to 1900, and everything below to 2000
                if year >= 0 and year <= 68:
                    year += 2000
                elif year >= 69 and year <= 99:
                    year += 1900
                return datetime(*((year,) + t[1:7])) - \
                       timedelta(seconds=t[-1] or 0)
            except (ValueError, OverflowError):
                return None 
Example 64
Project: flasky   Author: RoseOu   File: http.py    MIT License 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 65
Project: flasky   Author: RoseOu   File: http.py    MIT License 5 votes vote down vote up
def cookie_date(expires=None):
    """Formats the time to ensure compatibility with Netscape's cookie
    standard.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.

    :param expires: If provided that date is used, otherwise the current.
    """
    return _dump_date(expires, '-') 
Example 66
Project: flasky   Author: RoseOu   File: http.py    MIT License 5 votes vote down vote up
def http_date(timestamp=None):
    """Formats the time to match the RFC1123 date format.

    Accepts a floating point number expressed in seconds since the epoch in, a
    datetime object or a timetuple.  All times in UTC.  The :func:`parse_date`
    function can be used to parse such a date.

    Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

    :param timestamp: If provided that date is used, otherwise the current.
    """
    return _dump_date(timestamp, ' ') 
Example 67
Project: flasky   Author: RoseOu   File: atom.py    MIT License 5 votes vote down vote up
def format_iso8601(obj):
    """Format a datetime object for iso8601"""
    iso8601 = obj.isoformat()
    if obj.tzinfo:
        return iso8601
    return iso8601 + 'Z' 
Example 68
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def timestamp_to_datetime(self, ts):
        """Used to convert the timestamp from `get_timestamp` into a
        datetime object.
        """
        return datetime.utcfromtimestamp(ts + EPOCH) 
Example 69
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 5 votes vote down vote up
def get_issue_date(self, header):
        rv = header.get('iat')
        if isinstance(rv, number_types):
            return datetime.utcfromtimestamp(int(rv)) 
Example 70
Project: PathDump   Author: PathDump   File: pathdumpapi.py    Apache License 2.0 5 votes vote down vote up
def getFlows (linkID, timeRange):
    link_fltr = helper.buildLinkFilter (linkID)
    (stime_fltr, etime_fltr) = helper.buildTimeFilter (timeRange)
    data_fltr = helper.doAndFilters ([link_fltr, stime_fltr, etime_fltr])

    proj_fltr = {'sip': 1, 'sport': 1, 'dip': 1, 'dport': 1, 'proto': 1,
                 'path': 1, 'bytes': 1, 'pkts': 1, 'start': 1, 'end': 1,
                 '_id': 0}
    if data_fltr == '':
        cursor = collection.find (None, proj_fltr)
    else:
        cursor = collection.find (data_fltr, proj_fltr)
    flows = []
    for f in cursor:
        print "entry ",f
        flow = {'flowid': {}, 'path': None}
        flow['flowid']['sip'] = f['sip']
        flow['flowid']['sport'] = f['sport']
        flow['flowid']['dip'] = f['dip']
        flow['flowid']['dport'] = f['dport']
        flow['flowid']['proto'] = f['proto']
        flow['path'] = f['path']
        flow['bytes'] = f['bytes']
        flow['pkts'] = f['pkts']
        flow['start'] = (f['start'] - datetime(1970,1,1)).total_seconds()
        flow['end'] = (f['end'] - datetime(1970,1,1)).total_seconds()
        flows.append (flow)

    return flows 
Example 71
Project: PathDump   Author: PathDump   File: pathdumpapi.py    Apache License 2.0 5 votes vote down vote up
def getPoorTCPFlows (freq):
    tcpmon.init()
    poorFlows = tcpmon.updatePoorFlows (freq)
    flowIDs = []
    for fid in poorFlows:
        tokens = fid.split (':')
        if len (fields) != 5:
            continue
        flowid = {}
        flowid['sip']   = tokens[0]
        flowid['sport'] = tokens[1]
        flowid['dip']   = tokens[2]
        flowid['dport'] = tokens[3]
        flowid['proto'] = tokens[4]
        flowIDs.append (flowid)
    return flowIDs

# linkID = ('*', '16')
# timeRange = ('*', datetime.datetime(2015, 11, 9, 19, 10, 32, 765000))

# linkID = ('7', '16')
# timeRange = (datetime.datetime(2015, 11, 9, 19, 10, 30, 765000), datetime.datetime(2015, 11, 9, 19, 10, 32, 765000))

# linkID = ('7', '16')
# timeRange = ('*', '*')

# flowID = {'sip': '10.4.2.3', 'sport': '9000', 'dip': '10.3.2.3',
#           'dport': '60217', 'proto': '6'}

# flowID = {'sip': '*', 'sport': '9000', 'dip': '10.3.2.3',
#           'dport': '*', 'proto': '6'}
# Path = ['8-15', '15-18', '18-13', '13-6']
# Flow = {'flowid': flowID, 'path': Path}
# linkID = ('*', '*')
# timeRange = (datetime.datetime(2015, 11, 9, 19, 10, 30, 765000), datetime.datetime(2015, 11, 9, 19, 10, 32, 765000))
# getDuration (Flow, timeRange) 
Example 72
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_computations(self):
        a = self.theclass(2002, 1, 31)
        b = self.theclass(1956, 1, 31)
        diff = a-b
        self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4)))
        self.assertEqual(diff.seconds, 0)
        self.assertEqual(diff.microseconds, 0)
        a = self.theclass(2002, 3, 2, 17, 6)
        millisec = timedelta(0, 0, 1000)
        hour = timedelta(0, 3600)
        day = timedelta(1)
        week = timedelta(7)
        self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6))
        self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6))
        self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6))
        self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6))
        self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6))
        self.assertEqual(a - hour, a + -hour)
        self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6))
        self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6))
        self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6))
        self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6))
        self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6))
        self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6))
        self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6))
        self.assertEqual((a + week) - a, week)
        self.assertEqual((a + day) - a, day)
        self.assertEqual((a + hour) - a, hour)
        self.assertEqual((a + millisec) - a, millisec)
        self.assertEqual((a - week) - a, -week)
        self.assertEqual((a - day) - a, -day)
        self.assertEqual((a - hour) - a, -hour)
        self.assertEqual((a - millisec) - a, -millisec)
        self.assertEqual(a - (a + week), -week)
        self.assertEqual(a - (a + day), -day)
        self.assertEqual(a - (a + hour), -hour)
        self.assertEqual(a - (a + millisec), -millisec)
        self.assertEqual(a - (a - week), week)
        self.assertEqual(a - (a - day), day)
        self.assertEqual(a - (a - hour), hour)
        self.assertEqual(a - (a - millisec), millisec)
        self.assertEqual(a + (week + day + hour + millisec),
                         self.theclass(2002, 3, 10, 18, 6, 0, 1000))
        self.assertEqual(a + (week + day + hour + millisec),
                         (((a + week) + day) + hour) + millisec)
        self.assertEqual(a - (week + day + hour + millisec),
                         self.theclass(2002, 2, 22, 16, 5, 59, 999000))
        self.assertEqual(a - (week + day + hour + millisec),
                         (((a - week) - day) - hour) - millisec)
        # Add/sub ints, longs, floats should be illegal
        for i in 1, 1L, 1.0:
            self.assertRaises(TypeError, lambda: a+i)
            self.assertRaises(TypeError, lambda: a-i)
            self.assertRaises(TypeError, lambda: i+a)
            self.assertRaises(TypeError, lambda: i-a)

        # delta - datetime is senseless. 
Example 73
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_tz_aware_arithmetic(self):
        import random

        now = self.theclass.now()
        tz55 = FixedOffset(-330, "west 5:30")
        timeaware = now.time().replace(tzinfo=tz55)
        nowaware = self.theclass.combine(now.date(), timeaware)
        self.assertIs(nowaware.tzinfo, tz55)
        self.assertEqual(nowaware.timetz(), timeaware)

        # Can't mix aware and non-aware.
        self.assertRaises(TypeError, lambda: now - nowaware)
        self.assertRaises(TypeError, lambda: nowaware - now)

        # And adding datetime's doesn't make sense, aware or not.
        self.assertRaises(TypeError, lambda: now + nowaware)
        self.assertRaises(TypeError, lambda: nowaware + now)
        self.assertRaises(TypeError, lambda: nowaware + nowaware)

        # Subtracting should yield 0.
        self.assertEqual(now - now, timedelta(0))
        self.assertEqual(nowaware - nowaware, timedelta(0))

        # Adding a delta should preserve tzinfo.
        delta = timedelta(weeks=1, minutes=12, microseconds=5678)
        nowawareplus = nowaware + delta
        self.assertIs(nowaware.tzinfo, tz55)
        nowawareplus2 = delta + nowaware
        self.assertIs(nowawareplus2.tzinfo, tz55)
        self.assertEqual(nowawareplus, nowawareplus2)

        # that - delta should be what we started with, and that - what we
        # started with should be delta.
        diff = nowawareplus - delta
        self.assertIs(diff.tzinfo, tz55)
        self.assertEqual(nowaware, diff)
        self.assertRaises(TypeError, lambda: delta - nowawareplus)
        self.assertEqual(nowawareplus - nowaware, delta)

        # Make up a random timezone.
        tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
        # Attach it to nowawareplus.
        nowawareplus = nowawareplus.replace(tzinfo=tzr)
        self.assertIs(nowawareplus.tzinfo, tzr)
        # Make sure the difference takes the timezone adjustments into account.
        got = nowaware - nowawareplus
        # Expected:  (nowaware base - nowaware offset) -
        #            (nowawareplus base - nowawareplus offset) =
        #            (nowaware base - nowawareplus base) +
        #            (nowawareplus offset - nowaware offset) =
        #            -delta + nowawareplus offset - nowaware offset
        expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta
        self.assertEqual(got, expected)

        # Try max possible difference.
        min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min"))
        max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999,
                            tzinfo=FixedOffset(-1439, "max"))
        maxdiff = max - min
        self.assertEqual(maxdiff, self.theclass.max - self.theclass.min +
                                  timedelta(minutes=2*1439)) 
Example 74
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 4 votes vote down vote up
def unsign(self, value, max_age=None, return_timestamp=False):
        """Works like the regular :meth:`~Signer.unsign` but can also
        validate the time.  See the base docstring of the class for
        the general behavior.  If `return_timestamp` is set to `True`
        the timestamp of the signature will be returned as naive
        :class:`datetime.datetime` object in UTC.
        """
        try:
            result = Signer.unsign(self, value)
            sig_error = None
        except BadSignature as e:
            sig_error = e
            result = e.payload or b''
        sep = want_bytes(self.sep)

        # If there is no timestamp in the result there is something
        # seriously wrong.  In case there was a signature error, we raise
        # that one directly, otherwise we have a weird situation in which
        # we shouldn't have come except someone uses a time-based serializer
        # on non-timestamp data, so catch that.
        if not sep in result:
            if sig_error:
                raise sig_error
            raise BadTimeSignature('timestamp missing', payload=result)

        value, timestamp = result.rsplit(sep, 1)
        try:
            timestamp = bytes_to_int(base64_decode(timestamp))
        except Exception:
            timestamp = None

        # Signature is *not* okay.  Raise a proper error now that we have
        # split the value and the timestamp.
        if sig_error is not None:
            raise BadTimeSignature(text_type(sig_error), payload=value,
                                   date_signed=timestamp)

        # Signature was okay but the timestamp is actually not there or
        # malformed.  Should not happen, but well.  We handle it nonetheless
        if timestamp is None:
            raise BadTimeSignature('Malformed timestamp', payload=value)

        # Check timestamp is not older than max_age
        if max_age is not None:
            age = self.get_timestamp() - timestamp
            if age > max_age:
                raise SignatureExpired(
                    'Signature age %s > %s seconds' % (age, max_age),
                    payload=value,
                    date_signed=self.timestamp_to_datetime(timestamp))

        if return_timestamp:
            return value, self.timestamp_to_datetime(timestamp)
        return value 
Example 75
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: atom.py    Apache License 2.0 4 votes vote down vote up
def generate(self):
        """Return a generator that yields pieces of XML."""
        # atom demands either an author element in every entry or a global one
        if not self.author:
            if False in map(lambda e: bool(e.author), self.entries):
                self.author = ({'name': 'Unknown author'},)

        if not self.updated:
            dates = sorted([entry.updated for entry in self.entries])
            self.updated = dates and dates[-1] or datetime.utcnow()

        yield u'<?xml version="1.0" encoding="utf-8"?>\n'
        yield u'<feed xmlns="http://www.w3.org/2005/Atom">\n'
        yield '  ' + _make_text_block('title', self.title, self.title_type)
        yield u'  <id>%s</id>\n' % escape(self.id)
        yield u'  <updated>%s</updated>\n' % format_iso8601(self.updated)
        if self.url:
            yield u'  <link href="%s" />\n' % escape(self.url)
        if self.feed_url:
            yield u'  <link href="%s" rel="self" />\n' % \
                escape(self.feed_url)
        for link in self.links:
            yield u'  <link %s/>\n' % ''.join('%s="%s" ' % \
                (k, escape(link[k])) for k in link)
        for author in self.author:
            yield u'  <author>\n'
            yield u'    <name>%s</name>\n' % escape(author['name'])
            if 'uri' in author:
                yield u'    <uri>%s</uri>\n' % escape(author['uri'])
            if 'email' in author:
                yield '    <email>%s</email>\n' % escape(author['email'])
            yield '  </author>\n'
        if self.subtitle:
            yield '  ' + _make_text_block('subtitle', self.subtitle,
                                          self.subtitle_type)
        if self.icon:
            yield u'  <icon>%s</icon>\n' % escape(self.icon)
        if self.logo:
            yield u'  <logo>%s</logo>\n' % escape(self.logo)
        if self.rights:
            yield '  ' + _make_text_block('rights', self.rights,
                                          self.rights_type)
        generator_name, generator_url, generator_version = self.generator
        if generator_name or generator_url or generator_version:
            tmp = [u'  <generator']
            if generator_url:
                tmp.append(u' uri="%s"' % escape(generator_url))
            if generator_version:
                tmp.append(u' version="%s"' % escape(generator_version))
            tmp.append(u'>%s</generator>\n' % escape(generator_name))
            yield u''.join(tmp)
        for entry in self.entries:
            for line in entry.generate():
                yield u'  ' + line
        yield u'</feed>\n' 
Example 76
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: itsdangerous.py    Apache License 2.0 4 votes vote down vote up
def unsign(self, value, max_age=None, return_timestamp=False):
        """Works like the regular :meth:`~Signer.unsign` but can also
        validate the time.  See the base docstring of the class for
        the general behavior.  If `return_timestamp` is set to `True`
        the timestamp of the signature will be returned as naive
        :class:`datetime.datetime` object in UTC.
        """
        try:
            result = Signer.unsign(self, value)
            sig_error = None
        except BadSignature as e:
            sig_error = e
            result = e.payload or b''
        sep = want_bytes(self.sep)

        # If there is no timestamp in the result there is something
        # seriously wrong.  In case there was a signature error, we raise
        # that one directly, otherwise we have a weird situation in which
        # we shouldn't have come except someone uses a time-based serializer
        # on non-timestamp data, so catch that.
        if not sep in result:
            if sig_error:
                raise sig_error
            raise BadTimeSignature('timestamp missing', payload=result)

        value, timestamp = result.rsplit(sep, 1)
        try:
            timestamp = bytes_to_int(base64_decode(timestamp))
        except Exception:
            timestamp = None

        # Signature is *not* okay.  Raise a proper error now that we have
        # split the value and the timestamp.
        if sig_error is not None:
            raise BadTimeSignature(text_type(sig_error), payload=value,
                                   date_signed=timestamp)

        # Signature was okay but the timestamp is actually not there or
        # malformed.  Should not happen, but well.  We handle it nonetheless
        if timestamp is None:
            raise BadTimeSignature('Malformed timestamp', payload=value)

        # Check timestamp is not older than max_age
        if max_age is not None:
            age = self.get_timestamp() - timestamp
            if age > max_age:
                raise SignatureExpired(
                    'Signature age %s > %s seconds' % (age, max_age),
                    payload=value,
                    date_signed=self.timestamp_to_datetime(timestamp))

        if return_timestamp:
            return value, self.timestamp_to_datetime(timestamp)
        return value 
Example 77
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 4 votes vote down vote up
def trash(self):
        """Trash item in trash bin.

        Writes .trashinfo file, then moves path to trash bin."""

        # Write .trashinfo file first, so if it fails, we don't trash
        # the file, avoiding "orphaned" files in the bin.

        # Set trashed path (is this the best place to do this?)
        self.trashed_path = self.bin.files_path / self.original_path.name

        log.debug('Preparing to trash "%s" as "%s"', self.original_path, self.trashed_path)

        # Rename if necessary
        self._rename_if_necessary()

        # Set date_trashed
        self.date_trashed = datetime.utcnow()

        # Write trashinfo file
        self._write_trashinfo_file()

        # There seems to be no way to rename a path in Python without
        # potentially overwriting an existing path, so although we
        # change the basename if necessary above, there's still a
        # potential race condition that could cause an existing item
        # in the bin to be overwritten.

        # Actually, it might be possible to make a new hard link to
        # the file inside the trash bin, then unlink the original.
        # But that obviously won't work across filesystems, so maybe
        # it's not worth it.

        # Move path to trash
        try:
            # FIXME: Would Path.rename() suffice here, or does that not work across filesystems?
            shutil.move(self.original_path.as_posix(), self.trashed_path.as_posix())
        except Exception as e:
            log.error('Unable to move item "%s" to trashed path "%s": %s', self.original_path, self.trashed_path, e)

            # FIXME: Remove trashinfo file if trashing fails

            return False
        else:
            log.info('Trashed "%s" as: "%s"', self.original_path, self.trashed_path)

# ** Exceptions 
Example 78
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 79
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 4 votes vote down vote up
def sanitize_for_serialization(self, obj):
        """
        Builds a JSON POST object.

        If obj is None, return None.
        If obj is str, int, long, float, bool, return directly.
        If obj is datetime.datetime, datetime.date
            convert to string in iso8601 format.
        If obj is list, sanitize each element in the list.
        If obj is dict, return the dict.
        If obj is swagger model, return the properties dict.

        :param obj: The data to serialize.
        :return: The serialized form of data.
        """
        if obj is None:
            return None
        elif isinstance(obj, self.PRIMITIVE_TYPES):
            return obj
        elif isinstance(obj, list):
            return [self.sanitize_for_serialization(sub_obj)
                    for sub_obj in obj]
        elif isinstance(obj, tuple):
            return tuple(self.sanitize_for_serialization(sub_obj)
                         for sub_obj in obj)
        elif isinstance(obj, (datetime, date)):
            return obj.isoformat()

        if isinstance(obj, dict):
            obj_dict = obj
        else:
            # Convert model obj to dict except
            # attributes `swagger_types`, `attribute_map`
            # and attributes which value is not None.
            # Convert attribute name to json key in
            # model definition for request.
            obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
                        for attr, _ in iteritems(obj.swagger_types)
                        if getattr(obj, attr) is not None}

        return {key: self.sanitize_for_serialization(val)
                for key, val in iteritems(obj_dict)} 
Example 80
Project: flasky   Author: RoseOu   File: itsdangerous.py    MIT License 4 votes vote down vote up
def unsign(self, value, max_age=None, return_timestamp=False):
        """Works like the regular :meth:`~Signer.unsign` but can also
        validate the time.  See the base docstring of the class for
        the general behavior.  If `return_timestamp` is set to `True`
        the timestamp of the signature will be returned as naive
        :class:`datetime.datetime` object in UTC.
        """
        try:
            result = Signer.unsign(self, value)
            sig_error = None
        except BadSignature as e:
            sig_error = e
            result = e.payload or b''
        sep = want_bytes(self.sep)

        # If there is no timestamp in the result there is something
        # seriously wrong.  In case there was a signature error, we raise
        # that one directly, otherwise we have a weird situation in which
        # we shouldn't have come except someone uses a time-based serializer
        # on non-timestamp data, so catch that.
        if not sep in result:
            if sig_error:
                raise sig_error
            raise BadTimeSignature('timestamp missing', payload=result)

        value, timestamp = result.rsplit(sep, 1)
        try:
            timestamp = bytes_to_int(base64_decode(timestamp))
        except Exception:
            timestamp = None

        # Signature is *not* okay.  Raise a proper error now that we have
        # split the value and the timestamp.
        if sig_error is not None:
            raise BadTimeSignature(text_type(sig_error), payload=value,
                                   date_signed=timestamp)

        # Signature was okay but the timestamp is actually not there or
        # malformed.  Should not happen, but well.  We handle it nonetheless
        if timestamp is None:
            raise BadTimeSignature('Malformed timestamp', payload=value)

        # Check timestamp is not older than max_age
        if max_age is not None:
            age = self.get_timestamp() - timestamp
            if age > max_age:
                raise SignatureExpired(
                    'Signature age %s > %s seconds' % (age, max_age),
                    payload=value,
                    date_signed=self.timestamp_to_datetime(timestamp))

        if return_timestamp:
            return value, self.timestamp_to_datetime(timestamp)
        return value