Python datetime.datetime.time() Examples

The following are code examples for showing how to use datetime.datetime.time(). 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: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_issue23600(self):
        DSTDIFF = DSTOFFSET = timedelta(hours=1)

        class UKSummerTime(tzinfo):
            """Simple time zone which pretends to always be in summer time, since
                that's what shows the failure.
            """

            def utcoffset(self, dt):
                return DSTOFFSET

            def dst(self, dt):
                return DSTDIFF

            def tzname(self, dt):
                return 'UKSummerTime'

        tz = UKSummerTime()
        u = datetime(2014, 4, 26, 12, 1, tzinfo=tz)
        t = tz.fromutc(u)
        self.assertEqual(t - t.utcoffset(), u) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_extreme_ordinals(self):
        a = self.theclass.min
        a = self.theclass(a.year, a.month, a.day)  # get rid of time parts
        aord = a.toordinal()
        b = a.fromordinal(aord)
        self.assertEqual(a, b)

        self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1))

        b = a + timedelta(days=1)
        self.assertEqual(b.toordinal(), aord + 1)
        self.assertEqual(b, self.theclass.fromordinal(aord + 1))

        a = self.theclass.max
        a = self.theclass(a.year, a.month, a.day)  # get rid of time parts
        aord = a.toordinal()
        b = a.fromordinal(aord)
        self.assertEqual(a, b)

        self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1))

        b = a - timedelta(days=1)
        self.assertEqual(b.toordinal(), aord - 1)
        self.assertEqual(b, self.theclass.fromordinal(aord - 1)) 
Example 4
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_backdoor_resistance(self):
        # For fast unpickling, the constructor accepts a pickle byte 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 = b'1995-03-25'
        if not issubclass(self.theclass, datetime):
            base = base[:4]
        for month_byte in b'9', b'\0', b'\r', b'\xff':
            self.assertRaises(TypeError, self.theclass,
                                         base[:2] + month_byte + base[3:])
        if issubclass(self.theclass, datetime):
            # Good bytes, but bad tzinfo:
            with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'):
                self.theclass(bytes([1] * len(base)), 'EST')

        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] + bytes([ord_byte]) + base[3:]) 
Example 5
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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 6
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def convert_between_tz_and_utc(self, tz, utc):
        dston = self.dston.replace(tzinfo=tz)
        # Because 1:MM on the day DST ends is taken as being standard time,
        # there is no spelling in tz for the last hour of daylight time.
        # For purposes of the test, the last hour of DST is 0:MM, which is
        # taken as being daylight time (and 1:MM is taken as being standard
        # time).
        dstoff = self.dstoff.replace(tzinfo=tz)
        for delta in (timedelta(weeks=13),
                      DAY,
                      HOUR,
                      timedelta(minutes=1),
                      timedelta(microseconds=1)):

            self.checkinside(dston, tz, utc, dston, dstoff)
            for during in dston + delta, dstoff - delta:
                self.checkinside(during, tz, utc, dston, dstoff)

            self.checkoutside(dstoff, tz, utc)
            for outside in dston - delta, dstoff + delta:
                self.checkoutside(outside, tz, utc) 
Example 7
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_replace(self):
        t = time(0)
        dt = datetime(1, 1, 1)
        self.assertEqual(t.replace(fold=1).fold, 1)
        self.assertEqual(dt.replace(fold=1).fold, 1)
        self.assertEqual(t.replace(fold=0).fold, 0)
        self.assertEqual(dt.replace(fold=0).fold, 0)
        # Check that replacement of other fields does not change "fold".
        t = t.replace(fold=1, tzinfo=Eastern)
        dt = dt.replace(fold=1, tzinfo=Eastern)
        self.assertEqual(t.replace(tzinfo=None).fold, 1)
        self.assertEqual(dt.replace(tzinfo=None).fold, 1)
        # Out of bounds.
        with self.assertRaises(ValueError):
            t.replace(fold=2)
        with self.assertRaises(ValueError):
            dt.replace(fold=2)
        # Check that fold is a keyword-only argument
        with self.assertRaises(TypeError):
            t.replace(1, 1, 1, None, 1)
        with self.assertRaises(TypeError):
            dt.replace(1, 1, 1, 1, 1, 1, 1, None, 1) 
Example 8
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_gaps(self):
        tz = self.tz
        for dt, shift in tz.gaps():
            for x in [0 * shift, 0.5 * shift, shift - timedelta.resolution]:
                udt = dt + x
                udt = udt.replace(tzinfo=tz)
                ldt = tz.fromutc(udt)
                self.assertEqual(ldt.fold, 0)
                adt = udt.replace(tzinfo=timezone.utc).astimezone(tz)
                self.assertEquivDatetimes(adt, ldt)
                utcoffset = ldt.utcoffset()
                self.assertEqual(ldt.replace(tzinfo=None), udt.replace(tzinfo=None) + utcoffset)
                # Create a local time inside the gap
                ldt = tz.fromutc(dt.replace(tzinfo=tz)) - shift + x
                self.assertLess(ldt.replace(fold=1).utcoffset(),
                                ldt.replace(fold=0).utcoffset(),
                                "At %s." % ldt)

            for x in [-timedelta.resolution, shift]:
                udt = dt + x
                ldt = tz.fromutc(udt.replace(tzinfo=tz))
                self.assertEqual(ldt.fold, 0) 
Example 9
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 6 votes vote down vote up
def test_datetime_time(self):
        # test support for datetime.time
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql("test_time", self.conn, index=False)
        res = read_sql_table("test_time", self.conn)
        tm.assert_frame_equal(res, df)

        # GH8341
        # first, use the fallback to have the sqlite adapter put in place
        sqlite_conn = TestSQLiteFallback.connect()
        sql.to_sql(df, "test_time2", sqlite_conn, index=False)
        res = sql.read_sql_query("SELECT * FROM test_time2", sqlite_conn)
        ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
        tm.assert_frame_equal(ref, res)  # check if adapter is in place
        # then test if sqlalchemy is unaffected by the sqlite adapter
        sql.to_sql(df, "test_time3", self.conn, index=False)
        if self.flavor == "sqlite":
            res = sql.read_sql_query("SELECT * FROM test_time3", self.conn)
            ref = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(ref, res)
        res = sql.read_sql_table("test_time3", self.conn)
        tm.assert_frame_equal(df, res) 
Example 10
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 11
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 12
Project: SouthwestBot   Author: TAAPArthur   File: southwestScraper.py    MIT License 5 votes vote down vote up
def output(self, *message):
        time = datetime.now().strftime("%Y/%m/%d %H:%M:%S")+":"
        formattedMessage = str(message[0])
        for i in range(1, len(message)):
            formattedMessage += str(message[i])
        print(time, formattedMessage, flush=True) 
Example 13
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testUnknownOffsets(self):
        # This tzinfo behavior is required to make
        # datetime.time.{utcoffset, dst, tzname} work as documented.

        dst_tz = pytz.timezone('US/Eastern')

        # This information is not known when we don't have a date,
        # so return None per API.
        self.assertTrue(dst_tz.utcoffset(None) is None)
        self.assertTrue(dst_tz.dst(None) is None)
        # We don't know the abbreviation, but this is still a valid
        # tzname per the Python documentation.
        self.assertEqual(dst_tz.tzname(None), 'US/Eastern') 
Example 14
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testHourBefore(self):
        # Python's datetime library has a bug, where the hour before
        # a daylight savings transition is one hour out. For example,
        # at the end of US/Eastern daylight savings time, 01:00 EST
        # occurs twice (once at 05:00 UTC and once at 06:00 UTC),
        # whereas the first should actually be 01:00 EDT.
        # Note that this bug is by design - by accepting this ambiguity
        # for one hour one hour per year, an is_dst flag on datetime.time
        # became unnecessary.
        self._test_all(
                self.transition_time - timedelta(hours=1), self.after
                ) 
Example 15
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_belfast(self):
        # Belfast uses London time.
        self.assertTrue('Europe/Belfast' in pytz.all_timezones_set)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones_set) 
Example 16
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def start(self):
        """Start time of setup."""
        return self._start 
Example 17
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def start(self, val):
        try:
            self._start = to_datetime(val)
            self.USE_ALL_FILES = False
        except BaseException:
            if val is not None:
                logger.warning("Input %s could not be assigned to start time in "
                     "setup" % val) 
Example 18
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def stop(self):
        """Stop time of setup."""
        return self._stop 
Example 19
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def stop(self, val):
        try:
            self._stop = to_datetime(val)
            self.USE_ALL_FILES = False
        except BaseException:
            if val is not None:
                logger.warning("Input %s could not be assigned to stop time in "
                     "setup" % val) 
Example 20
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def USE_ALL_FILES(self):
        """File import option (boolean).

        If True, all files in image base folder are used (i.e. start / stop
        time stamps are disregarded)
        """
        return self.options["USE_ALL_FILES"] 
Example 21
Project: pyplis   Author: jgliss   File: setupclasses.py    GNU General Public License v3.0 5 votes vote down vote up
def base_info_check(self):
        """Check if all necessary information if available.

        Checks if path and times are valid

        Returns
        -------
            2-element tuple, containing

            - bool, True or False
            - str, information

        """
        ok = 1
        s = ("Base info check\n-----------------------------\n")
        if not self.base_dir or not exists(self.base_dir):
            ok = 0
            s += "BasePath does not exist\n"
        if not self.USE_ALL_FILES:
            if not isinstance(self.start, datetime) or\
                    not isinstance(self.stop, datetime):
                s += "Start / Stop info wrong datatype (need datetime)\n"
                ok = 0
            elif not self.start < self.stop:
                s += "Start time exceeds stop time"
                ok = 0
        return (ok, s) 
Example 22
Project: epg-dk.bundle   Author: ukdtom   File: test_tzinfo.py    The Unlicense 5 votes vote down vote up
def testUnknownOffsets(self):
        # This tzinfo behavior is required to make
        # datetime.time.{utcoffset, dst, tzname} work as documented.

        dst_tz = pytz.timezone('US/Eastern')

        # This information is not known when we don't have a date,
        # so return None per API.
        self.assertTrue(dst_tz.utcoffset(None) is None)
        self.assertTrue(dst_tz.dst(None) is None)
        # We don't know the abbreviation, but this is still a valid
        # tzname per the Python documentation.
        self.assertEqual(dst_tz.tzname(None), 'US/Eastern') 
Example 23
Project: epg-dk.bundle   Author: ukdtom   File: test_tzinfo.py    The Unlicense 5 votes vote down vote up
def testHourBefore(self):
        # Python's datetime library has a bug, where the hour before
        # a daylight saving transition is one hour out. For example,
        # at the end of US/Eastern daylight saving time, 01:00 EST
        # occurs twice (once at 05:00 UTC and once at 06:00 UTC),
        # whereas the first should actually be 01:00 EDT.
        # Note that this bug is by design - by accepting this ambiguity
        # for one hour one hour per year, an is_dst flag on datetime.time
        # became unnecessary.
        self._test_all(
                self.transition_time - timedelta(hours=1), self.after
                ) 
Example 24
Project: epg-dk.bundle   Author: ukdtom   File: test_tzinfo.py    The Unlicense 5 votes vote down vote up
def test_belfast(self):
        # Belfast uses London time.
        self.assertTrue('Europe/Belfast' in pytz.all_timezones_set)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones_set) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_name_cleanup(self):
        if '_Pure' in self.__class__.__name__:
            self.skipTest('Only run for Fast C implementation')

        datetime = datetime_module
        names = set(name for name in dir(datetime)
                    if not name.startswith('__') and not name.endswith('__'))
        allowed = set(['MAXYEAR', 'MINYEAR', 'date', 'datetime',
                       'datetime_CAPI', 'time', 'timedelta', 'timezone',
                       'tzinfo', 'sys'])
        self.assertEqual(names - allowed, set([])) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_deepcopy(self):
        for tz in self.ACDT, self.EST, timezone.min, timezone.max:
            tz_copy = copy.deepcopy(tz)
            self.assertEqual(tz_copy, tz)
        tz = timezone.utc
        tz_copy = copy.deepcopy(tz)
        self.assertIs(tz_copy, tz)


#############################################################################
# Base class for testing a particular aspect of timedelta, time, date and
# datetime comparisons. 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        # Try an arbitrary fixed value.
        year, month, day = 1999, 9, 19
        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
        d = self.theclass.fromtimestamp(ts)
        self.assertEqual(d.year, year)
        self.assertEqual(d.month, month)
        self.assertEqual(d.day, day) 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_more_ctime(self):
        # Test fields that TestDate doesn't touch.
        import time

        t = self.theclass(2002, 3, 2, 18, 3, 5, 123)
        self.assertEqual(t.ctime(), "Sat Mar  2 18:03:05 2002")
        # Oops!  The next line fails on Win2K under MSVC 6, so it's commented
        # out.  The difference is that t.ctime() produces " 2" for the day,
        # but platform ctime() produces "02" for the day.  According to
        # C99, t.ctime() is correct here.
        # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple())))

        # So test a case where that difference doesn't matter.
        t = self.theclass(2002, 3, 22, 18, 3, 5, 123)
        self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) 
Example 29
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        ts = time.time()
        expected = time.localtime(ts)
        got = self.theclass.fromtimestamp(ts)
        self.verify_field_equality(expected, got) 
Example 30
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_utcfromtimestamp(self):
        import time

        ts = time.time()
        expected = time.gmtime(ts)
        got = self.theclass.utcfromtimestamp(ts)
        self.verify_field_equality(expected, got)

    # Run with US-style DST rules: DST begins 2 a.m. on second Sunday in
    # March (M3.2.0) and ends 2 a.m. on first Sunday in November (M11.1.0). 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_extract(self):
        dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        self.assertEqual(dt.date(), date(2002, 3, 4))
        self.assertEqual(dt.time(), time(18, 45, 3, 1234)) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_combine(self):
        d = date(2002, 3, 4)
        t = time(18, 45, 3, 1234)
        expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234)
        combine = self.theclass.combine
        dt = combine(d, t)
        self.assertEqual(dt, expected)

        dt = combine(time=t, date=d)
        self.assertEqual(dt, expected)

        self.assertEqual(d, dt.date())
        self.assertEqual(t, dt.time())
        self.assertEqual(dt, combine(dt.date(), dt.time()))

        self.assertRaises(TypeError, combine) # need an arg
        self.assertRaises(TypeError, combine, d) # need two args
        self.assertRaises(TypeError, combine, t, d) # args reversed
        self.assertRaises(TypeError, combine, d, t, 1) # wrong tzinfo type
        self.assertRaises(TypeError, combine, d, t, 1, 2)  # too many args
        self.assertRaises(TypeError, combine, "date", "time") # wrong types
        self.assertRaises(TypeError, combine, d, "time") # wrong type
        self.assertRaises(TypeError, combine, "date", t) # wrong type

        # tzinfo= argument
        dt = combine(d, t, timezone.utc)
        self.assertIs(dt.tzinfo, timezone.utc)
        dt = combine(d, t, tzinfo=timezone.utc)
        self.assertIs(dt.tzinfo, timezone.utc)
        t = time()
        dt = combine(dt, t)
        self.assertEqual(dt.date(), d)
        self.assertEqual(dt.time(), t) 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromisoformat_ambiguous(self):
        # Test strings like 2018-01-31+12:15 (where +12:15 is not a time zone)
        separators = ['+', '-']
        for sep in separators:
            dt = self.theclass(2018, 1, 31, 12, 15)
            dtstr = dt.isoformat(sep=sep)

            with self.subTest(dtstr=dtstr):
                dt_rt = self.theclass.fromisoformat(dtstr)
                self.assertEqual(dt, dt_rt) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromisoformat_fails_datetime(self):
        # Test that fromisoformat() fails on invalid values
        bad_strs = [
            '',                             # Empty string
            '\ud800',                       # bpo-34454: Surrogate code point
            '2009.04-19T03',                # Wrong first separator
            '2009-04.19T03',                # Wrong second separator
            '2009-04-19T0a',                # Invalid hours
            '2009-04-19T03:1a:45',          # Invalid minutes
            '2009-04-19T03:15:4a',          # Invalid seconds
            '2009-04-19T03;15:45',          # Bad first time separator
            '2009-04-19T03:15;45',          # Bad second time separator
            '2009-04-19T03:15:4500:00',     # Bad time zone separator
            '2009-04-19T03:15:45.2345',     # Too many digits for milliseconds
            '2009-04-19T03:15:45.1234567',  # Too many digits for microseconds
            '2009-04-19T03:15:45.123456+24:30',    # Invalid time zone offset
            '2009-04-19T03:15:45.123456-24:30',    # Invalid negative offset
            '2009-04-10ᛇᛇᛇᛇᛇ12:15',         # Too many unicode separators
            '2009-04\ud80010T12:15',        # Surrogate char in date
            '2009-04-10T12\ud80015',        # Surrogate char in time
            '2009-04-19T1',                 # Incomplete hours
            '2009-04-19T12:3',              # Incomplete minutes
            '2009-04-19T12:30:4',           # Incomplete seconds
            '2009-04-19T12:',               # Ends with time separator
            '2009-04-19T12:30:',            # Ends with time separator
            '2009-04-19T12:30:45.',         # Ends with time separator
            '2009-04-19T12:30:45.123456+',  # Ends with timzone separator
            '2009-04-19T12:30:45.123456-',  # Ends with timzone separator
            '2009-04-19T12:30:45.123456-05:00a',    # Extra text
            '2009-04-19T12:30:45.123-05:00a',       # Extra text
            '2009-04-19T12:30:45-05:00a',           # Extra text
        ]

        for bad_str in bad_strs:
            with self.subTest(bad_str=bad_str):
                with self.assertRaises(ValueError):
                    self.theclass.fromisoformat(bad_str) 
Example 35
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        # time is always True.
        cls = self.theclass
        self.assertTrue(cls(1))
        self.assertTrue(cls(0, 1))
        self.assertTrue(cls(0, 0, 1))
        self.assertTrue(cls(0, 0, 0, 1))
        self.assertTrue(cls(0))
        self.assertTrue(cls()) 
Example 36
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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:])
        # Good bytes, but bad tzinfo:
        with self.assertRaisesRegex(TypeError, '^bad tzinfo state arg$'):
            self.theclass(bytes([1] * len(base)), 'EST')

# A mixin for classes with a tzinfo= argument.  Subclasses must define
# theclass as a class attribute, and theclass(1, 1, 1, tzinfo=whatever)
# must be legit (which is true for time and datetime). 
Example 37
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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 38
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_more_bool(self):
        # time is always True.
        cls = self.theclass

        t = cls(0, tzinfo=FixedOffset(-300, ""))
        self.assertTrue(t)

        t = cls(5, tzinfo=FixedOffset(-300, ""))
        self.assertTrue(t)

        t = cls(5, tzinfo=FixedOffset(300, ""))
        self.assertTrue(t)

        t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
        self.assertTrue(t) 
Example 39
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_mixed_compare(self):
        t1 = time(1, 2, 3)
        t2 = time(1, 2, 3)
        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.assertNotEqual(t1, t2)

        # In time 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 40
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromisoformat_fails(self):
        bad_strs = [
            '',                         # Empty string
            '12\ud80000',               # Invalid separator - surrogate char
            '12:',                      # Ends on a separator
            '12:30:',                   # Ends on a separator
            '12:30:15.',                # Ends on a separator
            '1',                        # Incomplete hours
            '12:3',                     # Incomplete minutes
            '12:30:1',                  # Incomplete seconds
            '1a:30:45.334034',          # Invalid character in hours
            '12:a0:45.334034',          # Invalid character in minutes
            '12:30:a5.334034',          # Invalid character in seconds
            '12:30:45.1234',            # Too many digits for milliseconds
            '12:30:45.1234567',         # Too many digits for microseconds
            '12:30:45.123456+24:30',    # Invalid time zone offset
            '12:30:45.123456-24:30',    # Invalid negative offset
            '12:30:45',                 # Uses full-width unicode colons
            '12:30:45․123456',          # Uses \u2024 in place of decimal point
            '12:30:45a',                # Extra at tend of basic time
            '12:30:45.123a',            # Extra at end of millisecond time
            '12:30:45.123456a',         # Extra at end of microsecond time
            '12:30:45.123456+12:00:30a',    # Extra at end of full time
        ]

        for bad_str in bad_strs:
            with self.subTest(bad_str=bad_str):
                with self.assertRaises(ValueError):
                    self.theclass.fromisoformat(bad_str) 
Example 41
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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 42
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_extract(self):
        met = FixedOffset(60, "MET")
        dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234, tzinfo=met)
        self.assertEqual(dt.date(), date(2002, 3, 4))
        self.assertEqual(dt.time(), time(18, 45, 3, 1234))
        self.assertEqual(dt.timetz(), time(18, 45, 3, 1234, tzinfo=met)) 
Example 43
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, 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, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None)) 
Example 44
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_tzinfo_utcfromtimestamp(self):
        import time
        meth = self.theclass.utcfromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword; for whatever reason,
        # utcfromtimestamp() doesn't accept a tzinfo argument.
        off42 = FixedOffset(42, "42")
        self.assertRaises(TypeError, meth, ts, off42)
        self.assertRaises(TypeError, meth, ts, tzinfo=off42) 
Example 45
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_more_astimezone(self):
        # The inherited test_astimezone covered some trivial and error cases.
        fnone = FixedOffset(None, "None")
        f44m = FixedOffset(44, "44")
        fm5h = FixedOffset(-timedelta(hours=5), "m300")

        dt = self.theclass.now(tz=f44m)
        self.assertIs(dt.tzinfo, f44m)
        # Replacing with degenerate tzinfo raises an exception.
        self.assertRaises(ValueError, dt.astimezone, fnone)
        # Replacing with same tzinfo makes no change.
        x = dt.astimezone(dt.tzinfo)
        self.assertIs(x.tzinfo, f44m)
        self.assertEqual(x.date(), dt.date())
        self.assertEqual(x.time(), dt.time())

        # Replacing with different tzinfo does adjust.
        got = dt.astimezone(fm5h)
        self.assertIs(got.tzinfo, fm5h)
        self.assertEqual(got.utcoffset(), timedelta(hours=-5))
        expected = dt - dt.utcoffset()  # in effect, convert to UTC
        expected += fm5h.utcoffset(dt)  # and from there to local time
        expected = expected.replace(tzinfo=fm5h) # and attach new tzinfo
        self.assertEqual(got.date(), expected.date())
        self.assertEqual(got.time(), expected.time())
        self.assertEqual(got.timetz(), expected.timetz())
        self.assertIs(got.tzinfo, expected.tzinfo)
        self.assertEqual(got, expected) 
Example 46
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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)

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

        # 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 47
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_extra_attributes(self):
        for x in [date.today(),
                  time(),
                  datetime.utcnow(),
                  timedelta(),
                  tzinfo(),
                  timezone(timedelta())]:
            with self.assertRaises(AttributeError):
                x.abc = 1 
Example 48
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def fromutc(self, dt):
        "datetime in UTC -> datetime in 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")
        # Returned value satisfies
        #          dt + ldt.utcoffset() = ldt
        off0 = dt.replace(fold=0).utcoffset()
        off1 = dt.replace(fold=1).utcoffset()
        if off0 is None or off1 is None or dt.dst() is None:
            raise ValueError
        if off0 == off1:
            ldt = dt + off0
            off1 = ldt.utcoffset()
            if off0 == off1:
                return ldt
        # Now, we discovered both possible offsets, so
        # we can just try four possible solutions:
        for off in [off0, off1]:
            ldt = dt + off
            if ldt.utcoffset() == off:
                return ldt
            ldt = ldt.replace(fold=1)
            if ldt.utcoffset() == off:
                return ldt

        raise ValueError("No suitable local time found")

# Reimplementing simplified US timezones to respect the "fold" flag: 
Example 49
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_constructors(self):
        t = time(0, fold=1)
        dt = datetime(1, 1, 1, fold=1)
        self.assertEqual(t.fold, 1)
        self.assertEqual(dt.fold, 1)
        with self.assertRaises(TypeError):
            time(0, 0, 0, 0, None, 0) 
Example 50
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_comparison(self):
        t = time(0)
        dt = datetime(1, 1, 1)
        self.assertEqual(t, t.replace(fold=1))
        self.assertEqual(dt, dt.replace(fold=1)) 
Example 51
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_hash(self):
        t = time(0)
        dt = datetime(1, 1, 1)
        self.assertEqual(hash(t), hash(t.replace(fold=1)))
        self.assertEqual(hash(dt), hash(dt.replace(fold=1))) 
Example 52
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_pickle_fold(self):
        t = time(fold=1)
        dt = datetime(1, 1, 1, fold=1)
        for pickler, unpickler, proto in pickle_choices:
            for x in [t, dt]:
                s = pickler.dumps(x, proto)
                y = unpickler.loads(s)
                self.assertEqual(x, y)
                self.assertEqual((0 if proto < 4 else x.fold), y.fold) 
Example 53
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        t = time(fold=1)
        dt = datetime(1, 1, 1, fold=1)
        self.assertEqual(repr(t), 'datetime.time(0, 0, fold=1)')
        self.assertEqual(repr(dt),
                         'datetime.datetime(1, 1, 1, 0, 0, fold=1)') 
Example 54
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_fromutc(self):
        # Let's first establish that things work in regular times.
        u_summer = datetime(2002, 10, 27, 6, tzinfo=Eastern2) - timedelta.resolution
        u_winter = datetime(2002, 10, 27, 7, tzinfo=Eastern2)
        t_summer = Eastern2.fromutc(u_summer)
        t_winter = Eastern2.fromutc(u_winter)
        self.assertEqual(t_summer, u_summer - 4 * HOUR)
        self.assertEqual(t_winter, u_winter - 5 * HOUR)
        self.assertEqual(t_summer.fold, 0)
        self.assertEqual(t_winter.fold, 0)

        # What happens in the fall-back fold?
        u = datetime(2002, 10, 27, 5, 30, tzinfo=Eastern2)
        t0 = Eastern2.fromutc(u)
        u += HOUR
        t1 = Eastern2.fromutc(u)
        self.assertEqual(t0, t1)
        self.assertEqual(t0.fold, 0)
        self.assertEqual(t1.fold, 1)
        # The tricky part is when u is in the local fold:
        u = datetime(2002, 10, 27, 1, 30, tzinfo=Eastern2)
        t = Eastern2.fromutc(u)
        self.assertEqual((t.day, t.hour), (26, 21))
        # .. or gets into the local fold after a standard time adjustment
        u = datetime(2002, 10, 27, 6, 30, tzinfo=Eastern2)
        t = Eastern2.fromutc(u)
        self.assertEqual((t.day, t.hour), (27, 1))

        # What happens in the spring-forward gap?
        u = datetime(2002, 4, 7, 2, 0, tzinfo=Eastern2)
        t = Eastern2.fromutc(u)
        self.assertEqual((t.day, t.hour), (6, 21)) 
Example 55
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def fromutc(self, dt):
        """datetime in UTC -> datetime in 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")

        timestamp = ((dt.toordinal() - self.EPOCHORDINAL) * 86400
                     + dt.hour * 3600
                     + dt.minute * 60
                     + dt.second)

        if timestamp < self.ut[1]:
            tti = self.ti[0]
            fold = 0
        else:
            idx = bisect.bisect_right(self.ut, timestamp)
            assert self.ut[idx-1] <= timestamp
            assert idx == len(self.ut) or timestamp < self.ut[idx]
            tti_prev, tti = self.ti[idx-2:idx]
            # Detect fold
            shift = tti_prev[0] - tti[0]
            fold = (shift > timedelta(0, timestamp - self.ut[idx-1]))
        dt += tti[0]
        if fold:
            return dt.replace(fold=1)
        else:
            return dt 
Example 56
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_check_date(self):
        class DateSubclass(date):
            pass

        d = date(2011, 1, 1)
        ds = DateSubclass(2011, 1, 1)
        dt = datetime(2011, 1, 1)

        is_date = _testcapi.datetime_check_date

        # Check the ones that should be valid
        self.assertTrue(is_date(d))
        self.assertTrue(is_date(dt))
        self.assertTrue(is_date(ds))
        self.assertTrue(is_date(d, True))

        # Check that the subclasses do not match exactly
        self.assertFalse(is_date(dt, True))
        self.assertFalse(is_date(ds, True))

        # Check that various other things are not dates at all
        args = [tuple(), list(), 1, '2011-01-01',
                timedelta(1), timezone.utc, time(12, 00)]
        for arg in args:
            for exact in (True, False):
                with self.subTest(arg=arg, exact=exact):
                    self.assertFalse(is_date(arg, exact)) 
Example 57
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 5 votes vote down vote up
def test_chunksize_read(self):
        df = DataFrame(np.random.randn(22, 5), columns=list("abcde"))
        df.to_sql("test_chunksize", self.conn, index=False)

        # reading the query in one time
        res1 = sql.read_sql_query("select * from test_chunksize", self.conn)

        # reading the query in chunks with read_sql_query
        res2 = DataFrame()
        i = 0
        sizes = [5, 5, 5, 5, 2]

        for chunk in sql.read_sql_query(
            "select * from test_chunksize", self.conn, chunksize=5
        ):
            res2 = concat([res2, chunk], ignore_index=True)
            assert len(chunk) == sizes[i]
            i += 1

        tm.assert_frame_equal(res1, res2)

        # reading the query in chunks with read_sql_query
        if self.mode == "sqlalchemy":
            res3 = DataFrame()
            i = 0
            sizes = [5, 5, 5, 5, 2]

            for chunk in sql.read_sql_table("test_chunksize", self.conn, chunksize=5):
                res3 = concat([res3, chunk], ignore_index=True)
                assert len(chunk) == sizes[i]
                i += 1

            tm.assert_frame_equal(res1, res3) 
Example 58
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 5 votes vote down vote up
def test_sqlalchemy_type_mapping(self):

        # Test Timestamp objects (no datetime64 because of timezone) (GH9085)
        df = DataFrame(
            {"time": to_datetime(["201412120154", "201412110254"], utc=True)}
        )
        db = sql.SQLDatabase(self.conn)
        table = sql.SQLTable("test_type", db, frame=df)
        # GH 9086: TIMESTAMP is the suggested type for datetimes with timezones
        assert isinstance(table.table.c["time"].type, sqltypes.TIMESTAMP) 
Example 59
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 5 votes vote down vote up
def test_sqlite_type_mapping(self):

        # Test Timestamp objects (no datetime64 because of timezone) (GH9085)
        df = DataFrame(
            {"time": to_datetime(["201412120154", "201412110254"], utc=True)}
        )
        db = sql.SQLiteDatabase(self.conn)
        table = sql.SQLiteTable("test_type", db, frame=df)
        schema = table.sql_schema()
        assert self._get_sqlite_column_type(schema, "time") == "TIMESTAMP"


# -----------------------------------------------------------------------------
# -- Database flavor specific tests 
Example 60
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_sql.py    MIT License 5 votes vote down vote up
def test_datetime_time(self):
        # test support for datetime.time, GH #8341
        df = DataFrame([time(9, 0, 0), time(9, 1, 30)], columns=["a"])
        df.to_sql("test_time", self.conn, index=False)
        res = read_sql_query("SELECT * FROM test_time", self.conn)
        if self.flavor == "sqlite":
            # comes back as strings
            expected = df.applymap(lambda _: _.strftime("%H:%M:%S.%f"))
            tm.assert_frame_equal(res, expected) 
Example 61
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def _local_timestamps(self):
        """
        Convert to an i8 (unix-like nanosecond timestamp) representation
        while keeping the local timezone and not using UTC.
        This is used to calculate time-of-day information as if the timestamps
        were timezone-naive.
        """
        return tzconversion.tz_convert(self.asi8, utc, self.tz) 
Example 62
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def time(self):
        """
        Returns numpy array of datetime.time. The time part of the Timestamps.
        """
        # If the Timestamps have a timezone that is not UTC,
        # convert them into their i8 representation while
        # keeping their timezone and not using UTC
        if self.tz is not None and not timezones.is_utc(self.tz):
            timestamps = self._local_timestamps()
        else:
            timestamps = self.asi8

        return tslib.ints_to_pydatetime(timestamps, box="time") 
Example 63
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def timetz(self):
        """
        Returns numpy array of datetime.time also containing timezone
        information. The time part of the Timestamps.
        """
        return tslib.ints_to_pydatetime(self.asi8, self.tz, box="time") 
Example 64
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def _infer_tz_from_endpoints(start, end, tz):
    """
    If a timezone is not explicitly given via `tz`, see if one can
    be inferred from the `start` and `end` endpoints.  If more than one
    of these inputs provides a timezone, require that they all agree.

    Parameters
    ----------
    start : Timestamp
    end : Timestamp
    tz : tzinfo or None

    Returns
    -------
    tz : tzinfo or None

    Raises
    ------
    TypeError : if start and end timezones do not agree
    """
    try:
        inferred_tz = timezones.infer_tzinfo(start, end)
    except Exception:
        raise TypeError(
            "Start and end cannot both be tz-aware with " "different timezones"
        )

    inferred_tz = timezones.maybe_get_tz(inferred_tz)
    tz = timezones.maybe_get_tz(tz)

    if tz is not None and inferred_tz is not None:
        if not timezones.tz_compare(inferred_tz, tz):
            raise AssertionError("Inferred time zone not equal to passed " "time zone")

    elif inferred_tz is not None:
        tz = inferred_tz

    return tz 
Example 65
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def _maybe_localize_point(ts, is_none, is_not_none, freq, tz, ambiguous, nonexistent):
    """
    Localize a start or end Timestamp to the timezone of the corresponding
    start or end Timestamp

    Parameters
    ----------
    ts : start or end Timestamp to potentially localize
    is_none : argument that should be None
    is_not_none : argument that should not be None
    freq : Tick, DateOffset, or None
    tz : str, timezone object or None
    ambiguous: str, localization behavior for ambiguous times
    nonexistent: str, localization behavior for nonexistent times

    Returns
    -------
    ts : Timestamp
    """
    # Make sure start and end are timezone localized if:
    # 1) freq = a Timedelta-like frequency (Tick)
    # 2) freq = None i.e. generating a linspaced range
    if is_none is None and is_not_none is not None:
        # Note: We can't ambiguous='infer' a singular ambiguous time; however,
        # we have historically defaulted ambiguous=False
        ambiguous = ambiguous if ambiguous != "infer" else False
        localize_args = {"ambiguous": ambiguous, "nonexistent": nonexistent, "tz": None}
        if isinstance(freq, Tick) or freq is None:
            localize_args["tz"] = tz
        ts = ts.tz_localize(**localize_args)
    return ts 
Example 66
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def snap(self, freq="S"):
        """
        Snap time stamps to nearest occurring frequency

        Returns
        -------
        DatetimeIndex
        """
        # Superdumb, punting on any optimizing
        freq = to_offset(freq)

        snapped = np.empty(len(self), dtype=_NS_DTYPE)

        for i, v in enumerate(self):
            s = v
            if not freq.onOffset(s):
                t0 = freq.rollback(s)
                t1 = freq.rollforward(s)
                if abs(s - t0) < abs(t1 - s):
                    s = t0
                else:
                    s = t1
            snapped[i] = s

        # we know it conforms; skip check
        return DatetimeIndex._simple_new(snapped, name=self.name, tz=self.tz, freq=freq) 
Example 67
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def get_value(self, series, key):
        """
        Fast lookup of value from 1-dimensional ndarray. Only use this if you
        know what you're doing
        """

        if isinstance(key, datetime):

            # needed to localize naive datetimes
            if self.tz is not None:
                if key.tzinfo is not None:
                    key = Timestamp(key).tz_convert(self.tz)
                else:
                    key = Timestamp(key).tz_localize(self.tz)

            return self.get_value_maybe_box(series, key)

        if isinstance(key, time):
            locs = self.indexer_at_time(key)
            return series.take(locs)

        try:
            return com.maybe_box(self, Index.get_value(self, series, key), series, key)
        except KeyError:
            try:
                loc = self._get_string_slice(key)
                return series[loc]
            except (TypeError, ValueError, KeyError):
                pass

            try:
                return self.get_value_maybe_box(series, key)
            except (TypeError, ValueError, KeyError):
                raise KeyError(key) 
Example 68
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def _maybe_cast_slice_bound(self, label, side, kind):
        """
        If label is a string, cast it to datetime according to resolution.

        Parameters
        ----------
        label : object
        side : {'left', 'right'}
        kind : {'ix', 'loc', 'getitem'}

        Returns
        -------
        label :  object

        Notes
        -----
        Value of `side` parameter should be validated in caller.

        """
        assert kind in ["ix", "loc", "getitem", None]

        if is_float(label) or isinstance(label, time) or is_integer(label):
            self._invalid_indexer("slice", label)

        if isinstance(label, str):
            freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
            _, parsed, reso = parsing.parse_time_string(label, freq)
            lower, upper = self._parsed_string_to_bounds(reso, parsed)
            # lower, upper form the half-open interval:
            #   [parsed, parsed + 1 freq)
            # because label may be passed to searchsorted
            # the bounds need swapped if index is reverse sorted and has a
            # length > 1 (is_monotonic_decreasing gives True for empty
            # and length 1 index)
            if self._is_strictly_monotonic_decreasing and len(self) > 1:
                return upper if side == "left" else lower
            return lower if side == "left" else upper
        else:
            return label 
Example 69
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 5 votes vote down vote up
def indexer_at_time(self, time, asof=False):
        """
        Return index locations of index values at particular time of day
        (e.g. 9:30AM).

        Parameters
        ----------
        time : datetime.time or string
            datetime.time or string in appropriate format ("%H:%M", "%H%M",
            "%I:%M%p", "%I%M%p", "%H:%M:%S", "%H%M%S", "%I:%M:%S%p",
            "%I%M%S%p").

        Returns
        -------
        values_at_time : array of integers

        See Also
        --------
        indexer_between_time, DataFrame.at_time
        """
        if asof:
            raise NotImplementedError("'asof' argument is not supported")

        if isinstance(time, str):
            from dateutil.parser import parse

            time = parse(time).time()

        if time.tzinfo:
            if self.tz is None:
                raise ValueError("Index must be timezone aware.")
            time_micros = self.tz_convert(time.tzinfo)._get_time_micros()
        else:
            time_micros = self._get_time_micros()
        micros = _time_to_micros(time)
        return (micros == time_micros).nonzero()[0] 
Example 70
Project: SouthwestBot   Author: TAAPArthur   File: southwestScraper.py    MIT License 4 votes vote down vote up
def getRecentFlights(self, savedUpComingFlights):

        tripLinks = []
        flights = []
        i = 0
        while True:
            tripElements = self.driver.find_elements_by_class_name("upcoming-trip-details-list-link")
            for tripElement in tripElements:
                tripLinks.append(tripElement.get_attribute("href"))
            nextButton = self.driver.find_element_by_class_name(
                "js-functional-bar-upcoming").find_element_by_class_name("js-right-arrow")
            if nextButton.get_attribute("disabled"):
                break
            else:
                self.waitForElementToToBeClickableByClass("js-right-arrow")
                nextButton.click()
                time.sleep(1)
            i += 1
            if i == 60:
                self.saveScreenshot("getRecentFlights.png")
                self.output("could not get recent flights")
                return[]
        for link in tripLinks:
            self.driver.get(link)
            self.output(link)

            confirmationNumber = self.waitForElementToHaveTextByClass("upcoming-details--confirmation-number")
            assert confirmationNumber != ""
            title = self.driver.find_element_by_class_name("upcoming-details--title").text
            rawDate = self.driver.find_elements_by_class_name("flight-details--date")

            firstRow = self.driver.find_elements_by_class_name("flight-details--first-row")
            lastRow = self.driver.find_elements_by_class_name("flight-details--row-last-child")
            assert len(rawDate) == len(firstRow)
            for i in range(len(rawDate)):
                date = rawDate[i].text.strip()
                assert date != ""

                startTime = firstRow[i].find_element_by_class_name("flight-details--trip-time").text.strip()
                endTime = lastRow[i].find_element_by_class_name("flight-details--trip-time").text.strip()
                origin = firstRow[i].find_element_by_class_name("flight-details--city").text
                dest = lastRow[i].find_element_by_class_name("flight-details--city").text
                departureTime = datetime.strptime(date+" "+startTime, "%m/%d/%y %I:%M%p")
                arrivalTime = datetime.strptime(date+" "+endTime, "%m/%d/%y %I:%M%p")
                flightNumber = int(firstRow[i].find_element_by_class_name("flight-details--flight-number").text)
                flight = Flight(title=title, confirmationNumber=confirmationNumber, departureTime=departureTime, arrivalTime=arrivalTime,
                                origin=origin, dest=dest, flightNumber=flightNumber, startDate=self.user.defaultDeltaStart, endDate=self.user.defaultDeltaEnd)

                if flight in savedUpComingFlights:
                    flight.copyMetadata(savedUpComingFlights[flight], self.user)

                flights.append(flight)

        return flights 
Example 71
Project: gw2pvo   Author: markruys   File: __main__.py    MIT License 4 votes vote down vote up
def run_once(args):
    global last_eday_kwh

    # Check if we only want to run during daylight
    if args.city:
        a = Astral()
        sun = a[args.city].sun(local=True)
        now = datetime.time(datetime.now())
        if now < sun['dawn'].time() or now > sun['dusk'].time():
            logging.debug("Skipped upload as it's night")
            return

    # Fetch the last reading from GoodWe
    gw = gw_api.GoodWeApi(args.gw_station_id, args.gw_account, args.gw_password)
    data = gw.getCurrentReadings()

    # Check if we want to abort when offline
    if args.skip_offline:
        if data['status'] == 'Offline':
            logging.debug("Skipped upload as the inverter is offline")
            return

    # Append reading to CSV file
    if args.csv:
        if data['status'] == 'Offline':
            logging.debug("Don't append offline data to CSV file")
        else:
            locale.setlocale(locale.LC_ALL, locale.getlocale())
            csv = gw_csv.GoodWeCSV(args.csv)
            csv.append(data)

    # Submit reading to PVOutput, if they differ from the previous set
    eday_kwh = data['eday_kwh']
    if data['pgrid_w'] == 0 and abs(eday_kwh - last_eday_kwh) < 0.001:
        logging.debug("Ignore unchanged reading")
    else:
        last_eday_kwh = eday_kwh

    if args.darksky_api_key:
        ds = ds_api.DarkSkyApi(args.darksky_api_key)
        data['temperature'] = ds.get_temperature(data['latitude'], data['longitude'])
        
    voltage = data['grid_voltage']
    if args.pv_voltage:
        voltage=data['pv_voltage']

    pvo = pvo_api.PVOutputApi(args.pvo_system_id, args.pvo_api_key)
    pvo.add_status(data['pgrid_w'], last_eday_kwh, data.get('temperature'), voltage) 
Example 72
Project: gw2pvo   Author: markruys   File: __main__.py    MIT License 4 votes vote down vote up
def run():

    # Parse command line arguments
    parser = argparse.ArgumentParser(description="Upload GoodWe power inverter data to PVOutput.org")
    parser.add_argument("--gw-station-id", help="GoodWe station ID", metavar='ID', required=True)
    parser.add_argument("--gw-account", help="GoodWe account", metavar='ACCOUNT', required=True)
    parser.add_argument("--gw-password", help="GoodWe password", metavar='PASSWORD', required=True)
    parser.add_argument("--pvo-system-id", help="PVOutput system ID", metavar='ID', required=True)
    parser.add_argument("--pvo-api-key", help="PVOutput API key", metavar='KEY', required=True)
    parser.add_argument("--pvo-interval", help="PVOutput interval in minutes", type=int, choices=[5, 10, 15])
    parser.add_argument("--darksky-api-key", help="Dark Sky Weather API key")
    parser.add_argument("--log", help="Set log level (default info)", choices=['debug', 'info', 'warning', 'critical'], default="info")
    parser.add_argument("--date", help="Copy all readings (max 14/90 days ago)", metavar='YYYY-MM-DD')
    parser.add_argument("--pv-voltage", help="Send pv voltage instead of grid voltage", action='store_true')
    parser.add_argument("--skip-offline", help="Skip uploads when inverter is offline", action='store_true')
    parser.add_argument("--city", help="Skip uploads from dusk till dawn")
    parser.add_argument('--csv', help="Append readings to a Excel compatible CSV file, DATE in the name will be replaced by the current date")
    parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
    args = parser.parse_args()

    # Configure the logging
    numeric_level = getattr(logging, args.log.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % loglevel)
    logging.basicConfig(format='%(levelname)-8s %(message)s', level=numeric_level)

    # Check if we're running the supported Python version
    if sys.version_info[0] != 3:
        logging.error("Please use Python 3 to run this script")
        sys.exit()

    # Check if we want to copy old data
    if args.date:
        copy(args)
        sys.exit()

    startTime = datetime.now()

    while True:
        try:
            run_once(args)
        except Exception as exp:
            logging.error(exp)

        if args.pvo_interval is None:
            break

        interval = args.pvo_interval * 60
        time.sleep(interval - (datetime.now() - startTime).seconds % interval) 
Example 73
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_subclass_alternate_constructors(self):
        # Test that alternate constructors call the constructor
        class DateSubclass(self.theclass):
            def __new__(cls, *args, **kwargs):
                result = self.theclass.__new__(cls, *args, **kwargs)
                result.extra = 7

                return result

        args = (2003, 4, 14)
        d_ord = 731319              # Equivalent ordinal date
        d_isoformat = '2003-04-14'  # Equivalent isoformat()

        base_d = DateSubclass(*args)
        self.assertIsInstance(base_d, DateSubclass)
        self.assertEqual(base_d.extra, 7)

        # Timestamp depends on time zone, so we'll calculate the equivalent here
        ts = datetime.combine(base_d, time(0)).timestamp()

        test_cases = [
            ('fromordinal', (d_ord,)),
            ('fromtimestamp', (ts,)),
            ('fromisoformat', (d_isoformat,)),
        ]

        for constr_name, constr_args in test_cases:
            for base_obj in (DateSubclass, base_d):
                # Test both the classmethod and method
                with self.subTest(base_obj_type=type(base_obj),
                                  constr_name=constr_name):
                    constr = getattr(base_obj, constr_name)

                    dt = constr(*constr_args)

                    # Test that it creates the right subclass
                    self.assertIsInstance(dt, DateSubclass)

                    # Test that it's equal to the base object
                    self.assertEqual(dt, base_d)

                    # Test that it called the constructor
                    self.assertEqual(dt.extra, 7) 
Example 74
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_subclass_alternate_constructors_datetime(self):
        # Test that alternate constructors call the constructor
        class DateTimeSubclass(self.theclass):
            def __new__(cls, *args, **kwargs):
                result = self.theclass.__new__(cls, *args, **kwargs)
                result.extra = 7

                return result

        args = (2003, 4, 14, 12, 30, 15, 123456)
        d_isoformat = '2003-04-14T12:30:15.123456'      # Equivalent isoformat()
        utc_ts = 1050323415.123456                      # UTC timestamp

        base_d = DateTimeSubclass(*args)
        self.assertIsInstance(base_d, DateTimeSubclass)
        self.assertEqual(base_d.extra, 7)

        # Timestamp depends on time zone, so we'll calculate the equivalent here
        ts = base_d.timestamp()

        test_cases = [
            ('fromtimestamp', (ts,)),
            # See https://bugs.python.org/issue32417
            # ('fromtimestamp', (ts, timezone.utc)),
            ('utcfromtimestamp', (utc_ts,)),
            ('fromisoformat', (d_isoformat,)),
            ('strptime', (d_isoformat, '%Y-%m-%dT%H:%M:%S.%f')),
            ('combine', (date(*args[0:3]), time(*args[3:]))),
        ]

        for constr_name, constr_args in test_cases:
            for base_obj in (DateTimeSubclass, base_d):
                # Test both the classmethod and method
                with self.subTest(base_obj_type=type(base_obj),
                                  constr_name=constr_name):
                    constr = getattr(base_obj, constr_name)

                    dt = constr(*constr_args)

                    # Test that it creates the right subclass
                    self.assertIsInstance(dt, DateTimeSubclass)

                    # Test that it's equal to the base object
                    self.assertEqual(dt, base_d.replace(tzinfo=None))

                    # Test that it called the constructor
                    self.assertEqual(dt.extra, 7) 
Example 75
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_aware_compare(self):
        cls = self.theclass

        # Ensure that utcoffset() gets ignored if the comparands have
        # the same tzinfo member.
        class OperandDependentOffset(tzinfo):
            def utcoffset(self, t):
                if t.minute < 10:
                    # d0 and d1 equal after adjustment
                    return timedelta(minutes=t.minute)
                else:
                    # d2 off in the weeds
                    return timedelta(minutes=59)

        base = cls(8, 9, 10, tzinfo=OperandDependentOffset())
        d0 = base.replace(minute=3)
        d1 = base.replace(minute=9)
        d2 = base.replace(minute=11)
        for x in d0, d1, d2:
            for y in d0, d1, d2:
                for op in lt, le, gt, ge, eq, ne:
                    got = op(x, y)
                    expected = op(x.minute, y.minute)
                    self.assertEqual(got, expected)

        # However, if they're different members, uctoffset is not ignored.
        # Note that a time can't actually have an operand-depedent offset,
        # though (and time.utcoffset() passes None to tzinfo.utcoffset()),
        # so skip this test for time.
        if cls is not time:
            d0 = base.replace(minute=3, tzinfo=OperandDependentOffset())
            d1 = base.replace(minute=9, tzinfo=OperandDependentOffset())
            d2 = base.replace(minute=11, tzinfo=OperandDependentOffset())
            for x in d0, d1, d2:
                for y in d0, d1, d2:
                    got = (x > y) - (x < y)
                    if (x is d0 or x is d1) and (y is d0 or y is d1):
                        expected = 0
                    elif x is y is d2:
                        expected = 0
                    elif x is d2:
                        expected = -1
                    else:
                        assert y is d2
                        expected = 1
                    self.assertEqual(got, expected)


# Testing time objects with a non-None tzinfo. 
Example 76
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def checkinside(self, dt, tz, utc, dston, dstoff):
        self.assertEqual(dt.dst(), HOUR)

        # Conversion to our own timezone is always an identity.
        self.assertEqual(dt.astimezone(tz), dt)

        asutc = dt.astimezone(utc)
        there_and_back = asutc.astimezone(tz)

        # Conversion to UTC and back isn't always an identity here,
        # because there are redundant spellings (in local time) of
        # UTC time when DST begins:  the clock jumps from 1:59:59
        # to 3:00:00, and a local time of 2:MM:SS doesn't really
        # make sense then.  The classes above treat 2:MM:SS as
        # daylight time then (it's "after 2am"), really an alias
        # for 1:MM:SS standard time.  The latter form is what
        # conversion back from UTC produces.
        if dt.date() == dston.date() and dt.hour == 2:
            # We're in the redundant hour, and coming back from
            # UTC gives the 1:MM:SS standard-time spelling.
            self.assertEqual(there_and_back + HOUR, dt)
            # Although during was considered to be in daylight
            # time, there_and_back is not.
            self.assertEqual(there_and_back.dst(), ZERO)
            # They're the same times in UTC.
            self.assertEqual(there_and_back.astimezone(utc),
                             dt.astimezone(utc))
        else:
            # We're not in the redundant hour.
            self.assertEqual(dt, there_and_back)

        # Because we have a redundant spelling when DST begins, there is
        # (unfortunately) an hour when DST ends that can't be spelled at all in
        # local time.  When DST ends, the clock jumps from 1:59 back to 1:00
        # again.  The hour 1:MM DST has no spelling then:  1:MM is taken to be
        # standard time.  1:MM DST == 0:MM EST, but 0:MM is taken to be
        # daylight time.  The hour 1:MM daylight == 0:MM standard can't be
        # expressed in local time.  Nevertheless, we want conversion back
        # from UTC to mimic the local clock's "repeat an hour" behavior.
        nexthour_utc = asutc + HOUR
        nexthour_tz = nexthour_utc.astimezone(tz)
        if dt.date() == dstoff.date() and dt.hour == 0:
            # We're in the hour before the last DST hour.  The last DST hour
            # is ineffable.  We want the conversion back to repeat 1:MM.
            self.assertEqual(nexthour_tz, dt.replace(hour=1))
            nexthour_utc += HOUR
            nexthour_tz = nexthour_utc.astimezone(tz)
            self.assertEqual(nexthour_tz, dt.replace(hour=1))
        else:
            self.assertEqual(nexthour_tz - dt, HOUR)

    # Check a time that's outside DST. 
Example 77
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_tricky(self):
        # 22:00 on day before daylight starts.
        fourback = self.dston - timedelta(hours=4)
        ninewest = FixedOffset(-9*60, "-0900", 0)
        fourback = fourback.replace(tzinfo=ninewest)
        # 22:00-0900 is 7:00 UTC == 2:00 EST == 3:00 DST.  Since it's "after
        # 2", we should get the 3 spelling.
        # If we plug 22:00 the day before into Eastern, it "looks like std
        # time", so its offset is returned as -5, and -5 - -9 = 4.  Adding 4
        # to 22:00 lands on 2:00, which makes no sense in local time (the
        # local clock jumps from 1 to 3).  The point here is to make sure we
        # get the 3 spelling.
        expected = self.dston.replace(hour=3)
        got = fourback.astimezone(Eastern).replace(tzinfo=None)
        self.assertEqual(expected, got)

        # Similar, but map to 6:00 UTC == 1:00 EST == 2:00 DST.  In that
        # case we want the 1:00 spelling.
        sixutc = self.dston.replace(hour=6, tzinfo=utc_real)
        # Now 6:00 "looks like daylight", so the offset wrt Eastern is -4,
        # and adding -4-0 == -4 gives the 2:00 spelling.  We want the 1:00 EST
        # spelling.
        expected = self.dston.replace(hour=1)
        got = sixutc.astimezone(Eastern).replace(tzinfo=None)
        self.assertEqual(expected, got)

        # Now on the day DST ends, we want "repeat an hour" behavior.
        #  UTC  4:MM  5:MM  6:MM  7:MM  checking these
        #  EST 23:MM  0:MM  1:MM  2:MM
        #  EDT  0:MM  1:MM  2:MM  3:MM
        # wall  0:MM  1:MM  1:MM  2:MM  against these
        for utc in utc_real, utc_fake:
            for tz in Eastern, Pacific:
                first_std_hour = self.dstoff - timedelta(hours=2) # 23:MM
                # Convert that to UTC.
                first_std_hour -= tz.utcoffset(None)
                # Adjust for possibly fake UTC.
                asutc = first_std_hour + utc.utcoffset(None)
                # First UTC hour to convert; this is 4:00 when utc=utc_real &
                # tz=Eastern.
                asutcbase = asutc.replace(tzinfo=utc)
                for tzhour in (0, 1, 1, 2):
                    expectedbase = self.dstoff.replace(hour=tzhour)
                    for minute in 0, 30, 59:
                        expected = expectedbase.replace(minute=minute)
                        asutc = asutcbase.replace(minute=minute)
                        astz = asutc.astimezone(tz)
                        self.assertEqual(astz.replace(tzinfo=None), expected)
                    asutcbase += HOUR 
Example 78
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 4 votes vote down vote up
def test_system_transitions(self):
        if ('Riyadh8' in self.zonename or
            # From tzdata NEWS file:
            # The files solar87, solar88, and solar89 are no longer distributed.
            # They were a negative experiment - that is, a demonstration that
            # tz data can represent solar time only with some difficulty and error.
            # Their presence in the distribution caused confusion, as Riyadh
            # civil time was generally not solar time in those years.
                self.zonename.startswith('right/')):
            self.skipTest("Skipping %s" % self.zonename)
        tz = self.tz
        TZ = os.environ.get('TZ')
        os.environ['TZ'] = self.zonename
        try:
            _time.tzset()
            for udt, shift in tz.transitions():
                if udt.year >= 2037:
                    # System support for times around the end of 32-bit time_t
                    # and later is flaky on many systems.
                    break
                s0 = (udt - datetime(1970, 1, 1)) // SEC
                ss = shift // SEC   # shift seconds
                for x in [-40 * 3600, -20*3600, -1, 0,
                          ss - 1, ss + 20 * 3600, ss + 40 * 3600]:
                    s = s0 + x
                    sdt = datetime.fromtimestamp(s)
                    tzdt = datetime.fromtimestamp(s, tz).replace(tzinfo=None)
                    self.assertEquivDatetimes(sdt, tzdt)
                    s1 = sdt.timestamp()
                    self.assertEqual(s, s1)
                if ss > 0:  # gap
                    # Create local time inside the gap
                    dt = datetime.fromtimestamp(s0) - shift / 2
                    ts0 = dt.timestamp()
                    ts1 = dt.replace(fold=1).timestamp()
                    self.assertEqual(ts0, s0 + ss / 2)
                    self.assertEqual(ts1, s0 - ss / 2)
        finally:
            if TZ is None:
                del os.environ['TZ']
            else:
                os.environ['TZ'] = TZ
            _time.tzset() 
Example 79
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 4 votes vote down vote up
def normalize(self):
        """
        Convert times to midnight.

        The time component of the date-time is converted to midnight i.e.
        00:00:00. This is useful in cases, when the time does not matter.
        Length is unaltered. The timezones are unaffected.

        This method is available on Series with datetime values under
        the ``.dt`` accessor, and directly on Datetime Array/Index.

        Returns
        -------
        DatetimeArray, DatetimeIndex or Series
            The same type as the original data. Series will have the same
            name and index. DatetimeIndex will have the same name.

        See Also
        --------
        floor : Floor the datetimes to the specified freq.
        ceil : Ceil the datetimes to the specified freq.
        round : Round the datetimes to the specified freq.

        Examples
        --------
        >>> idx = pd.date_range(start='2014-08-01 10:00', freq='H',
        ...                     periods=3, tz='Asia/Calcutta')
        >>> idx
        DatetimeIndex(['2014-08-01 10:00:00+05:30',
                       '2014-08-01 11:00:00+05:30',
                       '2014-08-01 12:00:00+05:30'],
                        dtype='datetime64[ns, Asia/Calcutta]', freq='H')
        >>> idx.normalize()
        DatetimeIndex(['2014-08-01 00:00:00+05:30',
                       '2014-08-01 00:00:00+05:30',
                       '2014-08-01 00:00:00+05:30'],
                       dtype='datetime64[ns, Asia/Calcutta]', freq=None)
        """
        if self.tz is None or timezones.is_utc(self.tz):
            not_null = ~self.isna()
            DAY_NS = ccalendar.DAY_SECONDS * 1000000000
            new_values = self.asi8.copy()
            adjustment = new_values[not_null] % DAY_NS
            new_values[not_null] = new_values[not_null] - adjustment
        else:
            new_values = conversion.normalize_i8_timestamps(self.asi8, self.tz)
        return type(self)._from_sequence(new_values, freq="infer").tz_localize(self.tz) 
Example 80
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: datetimes.py    MIT License 4 votes vote down vote up
def get_loc(self, key, method=None, tolerance=None):
        """
        Get integer location for requested label

        Returns
        -------
        loc : int
        """

        if tolerance is not None:
            # try converting tolerance now, so errors don't get swallowed by
            # the try/except clauses below
            tolerance = self._convert_tolerance(tolerance, np.asarray(key))

        if isinstance(key, datetime):
            # needed to localize naive datetimes
            if key.tzinfo is None:
                key = Timestamp(key, tz=self.tz)
            else:
                key = Timestamp(key).tz_convert(self.tz)
            return Index.get_loc(self, key, method, tolerance)

        elif isinstance(key, timedelta):
            # GH#20464
            raise TypeError(
                "Cannot index {cls} with {other}".format(
                    cls=type(self).__name__, other=type(key).__name__
                )
            )

        if isinstance(key, time):
            if method is not None:
                raise NotImplementedError(
                    "cannot yet lookup inexact labels " "when key is a time object"
                )
            return self.indexer_at_time(key)

        try:
            return Index.get_loc(self, key, method, tolerance)
        except (KeyError, ValueError, TypeError):
            try:
                return self._get_string_slice(key)
            except (TypeError, KeyError, ValueError, OverflowError):
                pass

            try:
                stamp = Timestamp(key)
                if stamp.tzinfo is not None and self.tz is not None:
                    stamp = stamp.tz_convert(self.tz)
                else:
                    stamp = stamp.tz_localize(self.tz)
                return Index.get_loc(self, stamp, method, tolerance)
            except KeyError:
                raise KeyError(key)
            except ValueError as e:
                # list-like tolerance size must match target index size
                if "list-like" in str(e):
                    raise e
                raise KeyError(key)