Python datetime.datetime.max() Examples

The following are code examples for showing how to use datetime.datetime.max(). 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: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser 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 2
Project: where   Author: kartverket   File: trf_snx_soln.py    MIT License 6 votes vote down vote up
def parse_solution_discontinuity(self, data):
        """Parser for SOLUTION/DISCONTINUITY data

        Converts the input data to a dictionary with items for each site, each containing start and end epochs for each
        solution. Only uses the position data, not the velocity data.

        Args:
            data (numpy.array):  Input data, raw data for SOLUTION/DISCONTINUITY block.
        """
        pos_data = data[data["pos_or_vel"] == "P"]
        pos_data["start_epoch"][np.equal(pos_data["start_epoch"], None)] = datetime.min
        pos_data["end_epoch"][np.equal(pos_data["end_epoch"], None)] = datetime.max

        for d, soln in zip(pos_data, pos_data["soln"].astype("i8")):
            site_key = d["site_code"]
            self.data.setdefault(site_key, dict())
            self.data[site_key].setdefault(soln, dict(start=d["start_epoch"], end=d["end_epoch"])) 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 6 votes vote down vote up
def test_overflow(self):
        tiny = timedelta.resolution

        td = timedelta.min + tiny
        td -= tiny  # no problem
        self.assertRaises(OverflowError, td.__sub__, tiny)
        self.assertRaises(OverflowError, td.__add__, -tiny)

        td = timedelta.max - tiny
        td += tiny  # no problem
        self.assertRaises(OverflowError, td.__add__, tiny)
        self.assertRaises(OverflowError, td.__sub__, -tiny)

        self.assertRaises(OverflowError, lambda: -timedelta.max)

        day = timedelta(1)
        self.assertRaises(OverflowError, day.__mul__, 10**9)
        self.assertRaises(OverflowError, day.__mul__, 1e9)
        self.assertRaises(OverflowError, day.__truediv__, 1e-20)
        self.assertRaises(OverflowError, day.__truediv__, 1e-10)
        self.assertRaises(OverflowError, day.__truediv__, 9e-10) 
Example 4
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 5
Project: typhon   Author: atmtools   File: fileset.py    MIT License 6 votes vote down vote up
def time_coverage(self, value):
        if self.single_file:
            if value is None:
                # The default for single file filesets:
                self._time_coverage = [
                    datetime.min,
                    datetime.max
                ]
            else:
                self._time_coverage = [
                    to_datetime(value[0]),
                    to_datetime(value[1]),
                ]
        elif value is not None:
            self._time_coverage = to_timedelta(value)
        else:
            self._time_coverage = None

        # Reset the info cache because some file information may have changed
        # now
        self.info_cache = {} 
Example 6
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.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 7
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 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 8
Project: airflow   Author: apache   File: test_dag_processing.py    Apache License 2.0 6 votes vote down vote up
def test_set_file_paths_when_processor_file_path_not_in_new_file_paths(self):
        manager = DagFileProcessorManager(
            dag_directory='directory',
            file_paths=['abc.txt'],
            max_runs=1,
            processor_factory=MagicMock().return_value,
            processor_timeout=timedelta.max,
            signal_conn=MagicMock(),
            async_mode=True)

        mock_processor = MagicMock()
        mock_processor.stop.side_effect = AttributeError(
            'DagFileProcessor object has no attribute stop')
        mock_processor.terminate.side_effect = None

        manager._processors['missing_file.txt'] = mock_processor
        manager._file_stats['missing_file.txt'] = DagFileStat(0, 0, None, None, 0)

        manager.set_file_paths(['abc.txt'])
        self.assertDictEqual(manager._processors, {}) 
Example 9
Project: airflow   Author: apache   File: test_dag_processing.py    Apache License 2.0 6 votes vote down vote up
def test_set_file_paths_when_processor_file_path_is_in_new_file_paths(self):
        manager = DagFileProcessorManager(
            dag_directory='directory',
            file_paths=['abc.txt'],
            max_runs=1,
            processor_factory=MagicMock().return_value,
            processor_timeout=timedelta.max,
            signal_conn=MagicMock(),
            async_mode=True)

        mock_processor = MagicMock()
        mock_processor.stop.side_effect = AttributeError(
            'DagFileProcessor object has no attribute stop')
        mock_processor.terminate.side_effect = None

        manager._processors['abc.txt'] = mock_processor

        manager.set_file_paths(['abc.txt'])
        self.assertDictEqual(manager._processors, {'abc.txt': mock_processor}) 
Example 10
Project: airflow   Author: apache   File: test_dag_processing.py    Apache License 2.0 6 votes vote down vote up
def test_kill_timed_out_processors_no_kill(self, mock_dag_file_processor, mock_pid):
        mock_pid.return_value = 1234
        manager = DagFileProcessorManager(
            dag_directory='directory',
            file_paths=['abc.txt'],
            max_runs=1,
            processor_factory=MagicMock().return_value,
            processor_timeout=timedelta(seconds=5),
            signal_conn=MagicMock(),
            async_mode=True)

        processor = DagFileProcessorProcess('abc.txt', False, [], [])
        processor._start_time = timezone.make_aware(datetime.max)
        manager._processors = {'abc.txt': processor}
        manager._kill_timed_out_processors()
        mock_dag_file_processor.kill.assert_not_called() 
Example 11
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 12
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_resolution_info(self):
        self.assertIsInstance(timedelta.min, timedelta)
        self.assertIsInstance(timedelta.max, timedelta)
        self.assertIsInstance(timedelta.resolution, timedelta)
        self.assertTrue(timedelta.max > timedelta.min)
        self.assertEqual(timedelta.min, timedelta(-999999999))
        self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
        self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) 
Example 13
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_overflow(self):
        tiny = timedelta.resolution

        td = timedelta.min + tiny
        td -= tiny  # no problem
        self.assertRaises(OverflowError, td.__sub__, tiny)
        self.assertRaises(OverflowError, td.__add__, -tiny)

        td = timedelta.max - tiny
        td += tiny  # no problem
        self.assertRaises(OverflowError, td.__add__, tiny)
        self.assertRaises(OverflowError, td.__sub__, -tiny)

        self.assertRaises(OverflowError, lambda: -timedelta.max) 
Example 14
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_overflow(self):
        tiny = self.theclass.resolution

        for delta in [tiny, timedelta(1), timedelta(2)]:
            dt = self.theclass.min + delta
            dt -= delta  # no problem
            self.assertRaises(OverflowError, dt.__sub__, delta)
            self.assertRaises(OverflowError, dt.__add__, -delta)

            dt = self.theclass.max - delta
            dt += delta  # no problem
            self.assertRaises(OverflowError, dt.__add__, delta)
            self.assertRaises(OverflowError, dt.__sub__, -delta) 
Example 15
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_timedelta(self):
        big = self.theclass.max - self.theclass.min
        # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
        n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
        # n == 315537897599999999 ~= 2**58.13
        justasbig = timedelta(0, 0, n)
        self.assertEqual(big, justasbig)
        self.assertEqual(self.theclass.min + big, self.theclass.max)
        self.assertEqual(self.theclass.max - big, self.theclass.min) 
Example 16
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        # All dates are considered true.
        self.assertTrue(self.theclass.min)
        self.assertTrue(self.theclass.max) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_resolution_info(self):
        self.assertIsInstance(self.theclass.min, self.theclass)
        self.assertIsInstance(self.theclass.max, self.theclass)
        self.assertIsInstance(self.theclass.resolution, timedelta)
        self.assertTrue(self.theclass.max > self.theclass.min) 
Example 18
Project: where   Author: kartverket   File: slr_eccentricity.py    MIT License 5 votes vote down vote up
def parse_site_eccentricity(self, data):
        for d in data:
            start_time = datetime.min if d["start_time"] is None else d["start_time"]
            end_time = datetime.max if d["end_time"] is None else d["end_time"]
            key = (start_time, end_time)
            if d["vector_type"] == "UNE":
                # Convert UNE to ENU
                self.data[d["site_code"]].setdefault(key, {}).update(
                    dict(vector=(d["vector_3"], d["vector_2"], d["vector_1"]), coord_type="ENU")
                )
            else:
                self.data[d["site_code"]].setdefault(key, {}).update(
                    dict(vector=(d["vector_1"], d["vector_2"], d["vector_3"]), coord_type=d["vector_type"])
                ) 
Example 19
Project: where   Author: kartverket   File: slr_handling_file.py    MIT License 5 votes vote down vote up
def parse_data_handling(self, data):
        for d in data:
            start_time = datetime.min if d["start_time"] is None else d["start_time"]
            end_time = datetime.max if d["end_time"] is None else d["end_time"]
            interval = (start_time, end_time)
            info = {"unit": d["unit"]}

            if d["e_value"]:
                try:
                    e_value = float(d["e_value"])
                except ValueError:
                    log.fatal("ILRS Data handling: Not able to convert value to float")
                info.update({"e_value": e_value})
            if d["std_dev"]:
                try:
                    std_dev = float(d["std_dev"])
                except ValueError:
                    log.fatal("ILRS Data handling: Not able to convert value to float")
                info.update({"std_dev": std_dev})

            # Unfortunately we have to deal with two different line formats.
            # Split the comments field in the second line format:
            # *CODE PT_ UNIT T _DATA_START_ __DATA_END__ M __E-VALUE___ STD_DEV ___COMMENTS______
            # *CODE PT_ UNIT T _DATA_START_ __DATA_END__ M __E-VALUE___ STD_DEV _E-RATE__ _CMNTS_
            try:
                info.update({"comments": d["comments2"], "e_rate": float(d["comments1"])})
            except ValueError:
                info.update({"comments": d["comments1"] + d["comments2"]})

            self.data.setdefault(d["site_code"], {}).setdefault(d["handling_code"], []).append((interval, info)) 
Example 20
Project: where   Author: kartverket   File: trf_snx.py    MIT License 5 votes vote down vote up
def parse_solution_epochs(self, data):
        for d, soln in zip(data, data["soln"].astype("i8")):
            site_key = d["site_code"]
            self.data[site_key].setdefault("pos_vel", dict())
            self.data[site_key]["pos_vel"][soln] = dict(start=datetime.min, end=datetime.max) 
Example 21
Project: where   Author: kartverket   File: trf_ssc.py    MIT License 5 votes vote down vote up
def parse_position(self, line, cache):
        """Parse the position line of ITRF data

        This gives the position (x,y,z) of the station. Converting position float.

        Args:
            line (Dict):  The fields of a line.
            cache (Dict): Dict that persists information.
        """
        data_fields = ("STAX", "STAY", "STAZ", "sigma_x", "sigma_y", "sigma_z", "soln", "start", "end")
        data_values = line.pop("data")
        line.update({k: v for k, v in itertools.zip_longest(data_fields, data_values.split())})
        line["ref_epoch"] = self.meta["ref_epoch"]
        cache["antenna_id"] = line["antenna_id"]
        line["soln"] = int(line["soln"]) if line["soln"] else 1
        cache["soln"] = line["soln"]
        pos_vel = dict()
        pos_vel.update({k: float(line.pop(k)) for k in list(line.keys()) if k.startswith("STA")})

        start = line.pop("start")
        if start and start[3:6] != "000":
            pos_vel["start"] = datetime.strptime(start[0:6], "%y:%j") + timedelta(seconds=int(start[7:]))
        else:
            pos_vel["start"] = datetime.min

        end = line.pop("end")
        if end and end[3:6] != "000":
            pos_vel["end"] = datetime.strptime(end[0:6], "%y:%j") + timedelta(seconds=int(end[7:]))
        else:
            pos_vel["end"] = datetime.max

        self.data.setdefault(cache["antenna_id"], dict())
        self.data[cache["antenna_id"]].update(line)
        self.data[cache["antenna_id"]].setdefault("pos_vel", dict())
        self.data[cache["antenna_id"]]["pos_vel"][line["soln"]] = pos_vel 
Example 22
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU 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 23
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_str(self):
        for tz in [self.ACDT, self.EST, timezone.utc,
                   timezone.min, timezone.max]:
            self.assertEqual(str(tz), tz.tzname(None)) 
Example 24
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        datetime = datetime_module
        for tz in [self.ACDT, self.EST, timezone.utc,
                   timezone.min, timezone.max]:
            # test round-trip
            tzrep = repr(tz)
            self.assertEqual(tz, eval(tzrep)) 
Example 25
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_class_members(self):
        limit = timedelta(hours=23, minutes=59)
        self.assertEqual(timezone.utc.utcoffset(None), ZERO)
        self.assertEqual(timezone.min.utcoffset(None), -limit)
        self.assertEqual(timezone.max.utcoffset(None), limit) 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_aware_datetime(self):
        # test that timezone instances can be used by datetime
        t = datetime(1, 1, 1)
        for tz in [timezone.min, timezone.max, timezone.utc]:
            self.assertEqual(tz.tzname(t),
                             t.replace(tzinfo=tz).tzname())
            self.assertEqual(tz.utcoffset(t),
                             t.replace(tzinfo=tz).utcoffset())
            self.assertEqual(tz.dst(t),
                             t.replace(tzinfo=tz).dst()) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_copy(self):
        for tz in self.ACDT, self.EST, timezone.min, timezone.max:
            tz_copy = copy.copy(tz)
            self.assertEqual(tz_copy, tz)
        tz = timezone.utc
        tz_copy = copy.copy(tz)
        self.assertIs(tz_copy, tz) 
Example 28
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 29
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_resolution_info(self):
        self.assertIsInstance(timedelta.min, timedelta)
        self.assertIsInstance(timedelta.max, timedelta)
        self.assertIsInstance(timedelta.resolution, timedelta)
        self.assertTrue(timedelta.max > timedelta.min)
        self.assertEqual(timedelta.min, timedelta(-999999999))
        self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
        self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) 
Example 30
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_resolution_info(self):
        # XXX: Should min and max respect subclassing?
        if issubclass(self.theclass, datetime):
            expected_class = datetime
        else:
            expected_class = date
        self.assertIsInstance(self.theclass.min, expected_class)
        self.assertIsInstance(self.theclass.max, expected_class)
        self.assertIsInstance(self.theclass.resolution, timedelta)
        self.assertTrue(self.theclass.max > self.theclass.min) 
Example 31
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_extreme_timedelta(self):
        big = self.theclass.max - self.theclass.min
        # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
        n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
        # n == 315537897599999999 ~= 2**58.13
        justasbig = timedelta(0, 0, n)
        self.assertEqual(big, justasbig)
        self.assertEqual(self.theclass.min + big, self.theclass.max)
        self.assertEqual(self.theclass.max - big, self.theclass.min) 
Example 32
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        # All dates are considered true.
        self.assertTrue(self.theclass.min)
        self.assertTrue(self.theclass.max) 
Example 33
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_timestamp_limits(self):
        # minimum timestamp
        min_dt = self.theclass.min.replace(tzinfo=timezone.utc)
        min_ts = min_dt.timestamp()
        try:
            # date 0001-01-01 00:00:00+00:00: timestamp=-62135596800
            self.assertEqual(self.theclass.fromtimestamp(min_ts, tz=timezone.utc),
                             min_dt)
        except (OverflowError, OSError) as exc:
            # the date 0001-01-01 doesn't fit into 32-bit time_t,
            # or platform doesn't support such very old date
            self.skipTest(str(exc))

        # maximum timestamp: set seconds to zero to avoid rounding issues
        max_dt = self.theclass.max.replace(tzinfo=timezone.utc,
                                           second=0, microsecond=0)
        max_ts = max_dt.timestamp()
        # date 9999-12-31 23:59:00+00:00: timestamp 253402300740
        self.assertEqual(self.theclass.fromtimestamp(max_ts, tz=timezone.utc),
                         max_dt)

        # number of seconds greater than 1 year: make sure that the new date
        # is not valid in datetime.datetime limits
        delta = 3600 * 24 * 400

        # too small
        ts = min_ts - delta
        # converting a Python int to C time_t can raise a OverflowError,
        # especially on 32-bit platforms.
        with self.assertRaises((ValueError, OverflowError)):
            self.theclass.fromtimestamp(ts)
        with self.assertRaises((ValueError, OverflowError)):
            self.theclass.utcfromtimestamp(ts)

        # too big
        ts = max_dt.timestamp() + delta
        with self.assertRaises((ValueError, OverflowError)):
            self.theclass.fromtimestamp(ts)
        with self.assertRaises((ValueError, OverflowError)):
            self.theclass.utcfromtimestamp(ts) 
Example 34
Project: NiujiaoDebugger   Author: MrSrc   File: datetimetester.py    GNU General Public License v3.0 5 votes vote down vote up
def test_resolution_info(self):
        self.assertIsInstance(self.theclass.min, self.theclass)
        self.assertIsInstance(self.theclass.max, self.theclass)
        self.assertIsInstance(self.theclass.resolution, timedelta)
        self.assertTrue(self.theclass.max > self.theclass.min) 
Example 35
Project: python-zhmcclient   Author: zhmcclient   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def find_max_value(test_func, initial_value):
    """
    Starting from an initial number (integer or float), find the maximum value
    for which the test function does not yet fail, and return that maximum
    value.
    """
    assert isinstance(initial_value, int) and initial_value > 0

    fails = FailsArray(test_func)
    value = initial_value

    # Advance the value exponentially beyond the max value
    while fails[value] == 0:
        value *= 2

    # Search for the exact max value in the previous range. We search for the
    # boundary where the fails array goes from 0 to 1.
    boundary = 0.5
    value = binary_search(fails, boundary, value // 2, value)
    max_value = value - 1

    # Verify that we found exactly the maximum:
    assert fails[max_value] == 0 and fails[max_value + 1] == 1, \
        "max_value={}, fails[+-2]: {}, {}, {}, {}, {}".\
        format(max_value, fails[max_value - 2], fails[max_value - 1],
               fails[max_value], fails[max_value + 1], fails[max_value + 2])

    return max_value 
Example 36
Project: python-zhmcclient   Author: zhmcclient   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def x_test_print_datetime_max(self):
        """Print datetime.max."""
        print("\nMax value for Python datetime (datetime.max): {!r}".
              format(datetime.max))
        sys.stdout.flush() 
Example 37
Project: python-zhmcclient   Author: zhmcclient   File: test_utils.py    Apache License 2.0 5 votes vote down vote up
def test_datetime_max(self):
        """Test timestamp_from_datetime() with datetime.max."""

        # The test is that it does not raise an exception:
        timestamp_from_datetime(datetime.max) 
Example 38
Project: octopuscloud   Author: christianbaun   File: result.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, batch_name, sd, mimetype_files=None):
        self.sd = sd
        self.batch = batch_name
        self.log_fp = None
        self.num_files = 0
        self.total_time = 0
        self.min_time = timedelta.max
        self.max_time = timedelta.min
        self.earliest_time = datetime.max
        self.latest_time = datetime.min
        self.queue = self.sd.get_obj('output_queue')
        self.domain = self.sd.get_obj('output_domain') 
Example 39
Project: flowlogs-reader   Author: obsrvbl   File: aggregation.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.start = datetime.max
        self.end = datetime.min
        self.packets = 0
        self.bytes = 0 
Example 40
Project: Lyff   Author: akashlevy   File: result.py    MIT License 5 votes vote down vote up
def __init__(self, batch_name, sd, mimetype_files=None):
        self.sd = sd
        self.batch = batch_name
        self.log_fp = None
        self.num_files = 0
        self.total_time = 0
        self.min_time = timedelta.max
        self.max_time = timedelta.min
        self.earliest_time = datetime.max
        self.latest_time = datetime.min
        self.queue = self.sd.get_obj('output_queue')
        self.domain = self.sd.get_obj('output_domain') 
Example 41
Project: typhon   Author: atmtools   File: collocator.py    MIT License 5 votes vote down vote up
def _get_common_time_period(
            primary, secondary, max_interval, start, end):
        max_interval = pd.Timedelta(max_interval)

        # We want to select a common time window from both datasets,
        # aligned to the primary's time coverage. Because xarray has a
        # very annoying bug in time retrieving
        # (https://github.com/pydata/xarray/issues/1240), this is a
        # little bit cumbersome:
        common_start = max(
            start,
            pd.Timestamp(primary.time.min().item(0)) - max_interval,
            pd.Timestamp(secondary.time.min().item(0)) - max_interval
        )
        common_end = min(
            end,
            pd.Timestamp(primary.time.max().item(0)) + max_interval,
            pd.Timestamp(secondary.time.max().item(0)) + max_interval
        )

        primary_period = primary.time.where(
            (primary.time.values >= np.datetime64(common_start))
            & (primary.time.values <= np.datetime64(common_end))
        ).dropna(primary.time.dims[0])

        secondary_period = secondary.time.where(
            (secondary.time.values >= np.datetime64(common_start))
            & (secondary.time.values <= np.datetime64(common_end))
        ).dropna(secondary.time.dims[0])

        return primary_period, secondary_period 
Example 42
Project: typhon   Author: atmtools   File: collocator.py    MIT License 5 votes vote down vote up
def _bin_pairs(chunk1_start, chunk1, primary, secondary, max_interval):
        """"""
        chunk2_start = chunk1_start - max_interval
        chunk2_end = chunk1.index.max() + max_interval
        offset1 = primary.index.searchsorted(chunk1_start)
        offset2 = secondary.index.searchsorted(chunk2_start)
        chunk2 = secondary.loc[chunk2_start:chunk2_end]
        return offset1, chunk1, offset2, chunk2 
Example 43
Project: typhon   Author: atmtools   File: fileset.py    MIT License 5 votes vote down vote up
def __init__(self, fileset, start, end, *args):
        if start == datetime.min and end >= datetime.max-timedelta(seconds=1):
            message = f"Found no files for {fileset.name}!"
        else:
            message = f"Found no files for {fileset.name} between {start} " \
                      f"and {end}!"

        message += f"\nPath: {fileset.path}\nCheck the path for misspellings" \
                   f" and whether there are files in this time period."
        Exception.__init__(self, message, *args) 
Example 44
Project: typhon   Author: atmtools   File: fileset.py    MIT License 5 votes vote down vote up
def _get_superior_time_resolution(placeholders, ):
        """Get the superior time resolution of all placeholders.

        Examples:
            The superior time resolution of seconds are minutes, of hours are
            days, etc.

        Args:
            placeholders: A list or dictionary with placeholders.

        Returns:
            A pandas compatible frequency string or None if the superior time
            resolution is higher than a year.
        """
        # All placeholders from which we know the resolution:
        placeholders = set(placeholders).intersection(
            FileSet._temporal_resolution
        )

        if not placeholders:
            return None

        highest_resolution = max(
            (FileSet._temporal_resolution[tp] for tp in placeholders),
        )

        highest_resolution_index = list(
            FileSet._temporal_resolution.values()).index(highest_resolution)

        if highest_resolution_index == 0:
            return None

        resolutions = list(FileSet._temporal_resolution.values())
        superior_resolution = resolutions[highest_resolution_index - 1]

        return pd.Timedelta(superior_resolution).to_pytimedelta() 
Example 45
Project: mars   Author: mars-project   File: worker_pages.py    Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.owner_to_ticker = OrderedDict()
        self.unfinished_to_indexes = dict()
        self.base_indexes = defaultdict(lambda: 0)

        self.min_left = datetime.max
        self.max_right = datetime.min
        self.min_bottom = 0xffffffff
        self.max_top = 0 
Example 46
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.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 47
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_resolution_info(self):
        self.assertIsInstance(timedelta.min, timedelta)
        self.assertIsInstance(timedelta.max, timedelta)
        self.assertIsInstance(timedelta.resolution, timedelta)
        self.assertTrue(timedelta.max > timedelta.min)
        self.assertEqual(timedelta.min, timedelta(-999999999))
        self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
        self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) 
Example 48
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_overflow(self):
        tiny = timedelta.resolution

        td = timedelta.min + tiny
        td -= tiny  # no problem
        self.assertRaises(OverflowError, td.__sub__, tiny)
        self.assertRaises(OverflowError, td.__add__, -tiny)

        td = timedelta.max - tiny
        td += tiny  # no problem
        self.assertRaises(OverflowError, td.__add__, tiny)
        self.assertRaises(OverflowError, td.__sub__, -tiny)

        self.assertRaises(OverflowError, lambda: -timedelta.max) 
Example 49
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_overflow(self):
        tiny = self.theclass.resolution

        for delta in [tiny, timedelta(1), timedelta(2)]:
            dt = self.theclass.min + delta
            dt -= delta  # no problem
            self.assertRaises(OverflowError, dt.__sub__, delta)
            self.assertRaises(OverflowError, dt.__add__, -delta)

            dt = self.theclass.max - delta
            dt += delta  # no problem
            self.assertRaises(OverflowError, dt.__add__, delta)
            self.assertRaises(OverflowError, dt.__sub__, -delta) 
Example 50
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_extreme_timedelta(self):
        big = self.theclass.max - self.theclass.min
        # 3652058 days, 23 hours, 59 minutes, 59 seconds, 999999 microseconds
        n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds
        # n == 315537897599999999 ~= 2**58.13
        justasbig = timedelta(0, 0, n)
        self.assertEqual(big, justasbig)
        self.assertEqual(self.theclass.min + big, self.theclass.max)
        self.assertEqual(self.theclass.max - big, self.theclass.min)