我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用datetime.combine()。
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) # too many args self.assertRaises(TypeError, combine, "date", "time") # wrong types
def test_NaT_methods(self): # GH 9513 raise_methods = ['astimezone', 'combine', 'ctime', 'dst', 'fromordinal', 'fromtimestamp', 'isocalendar', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'toordinal', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple'] nat_methods = ['date', 'now', 'replace', 'to_datetime', 'today'] nan_methods = ['weekday', 'isoweekday'] for method in raise_methods: if hasattr(NaT, method): self.assertRaises(ValueError, getattr(NaT, method)) for method in nan_methods: if hasattr(NaT, method): self.assertTrue(np.isnan(getattr(NaT, method)())) for method in nat_methods: if hasattr(NaT, method): self.assertIs(getattr(NaT, method)(), NaT) # GH 12300 self.assertEqual(NaT.isoformat(), 'NaT')
def test_class_ops_pytz(self): tm._skip_if_no_pytz() from pytz import timezone def compare(x, y): self.assertEqual(int(Timestamp(x).value / 1e9), int(Timestamp(y).value / 1e9)) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(timezone('UTC'))) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
def test_class_ops_dateutil(self): tm._skip_if_no_dateutil() from dateutil.tz import tzutc def compare(x, y): self.assertEqual(int(np.round(Timestamp(x).value / 1e9)), int(np.round(Timestamp(y).value / 1e9))) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(tzutc())) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
def _CombineDateAndTime(date, time, tzinfo): """Creates a datetime object from date and time objects. This is similar to the datetime.combine method, but its timezone calculations are designed to work with pytz. Arguments: date: a datetime.date object, in any timezone time: a datetime.time object, in any timezone tzinfo: a pytz timezone object, or None Returns: a datetime.datetime object, in the timezone 'tzinfo' """ naive_result = datetime.datetime( date.year, date.month, date.day, time.hour, time.minute, time.second) if tzinfo is None: return naive_result try: return tzinfo.localize(naive_result, is_dst=None) except AmbiguousTimeError: return min(tzinfo.localize(naive_result, is_dst=True), tzinfo.localize(naive_result, is_dst=False)) except NonExistentTimeError: while True: naive_result += datetime.timedelta(minutes=1) try: return tzinfo.localize(naive_result, is_dst=None) except NonExistentTimeError: pass
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))
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.assertTrue(as_date.__eq__(as_datetime)) different_day = (as_date.day + 1) % 20 + 1 self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day))) # And date should compare with other subclasses of date. If a # subclass wants to stop this, it's up to the subclass to do so. date_sc = SubclassDate(as_date.year, as_date.month, as_date.day) self.assertEqual(as_date, date_sc) self.assertEqual(date_sc, as_date) # Ditto for datetimes. datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, as_date.day, 0, 0, 0) self.assertEqual(as_datetime, datetime_sc) self.assertEqual(datetime_sc, as_datetime)
def test_bug_1028306(self): # Trying to compare a date to a datetime should act like a mixed- # type comparison, despite that datetime is a subclass of date. as_date = date.today() as_datetime = datetime.combine(as_date, time()) self.assertTrue(as_date != as_datetime) self.assertTrue(as_datetime != as_date) self.assertFalse(as_date == as_datetime) self.assertFalse(as_datetime == as_date) self.assertRaises(TypeError, lambda: as_date < as_datetime) self.assertRaises(TypeError, lambda: as_datetime < as_date) self.assertRaises(TypeError, lambda: as_date <= as_datetime) self.assertRaises(TypeError, lambda: as_datetime <= as_date) self.assertRaises(TypeError, lambda: as_date > as_datetime) self.assertRaises(TypeError, lambda: as_datetime > as_date) self.assertRaises(TypeError, lambda: as_date >= as_datetime) self.assertRaises(TypeError, lambda: as_datetime >= as_date) # Neverthelss, comparison should work with the base-class (date) # projection if use of a date method is forced. self.assertTrue(as_date.__eq__(as_datetime)) different_day = (as_date.day + 1) % 20 + 1 self.assertFalse(as_date.__eq__(as_datetime.replace(day=different_day))) # And date should compare with other subclasses of date. If a # subclass wants to stop this, it's up to the subclass to do so. date_sc = SubclassDate(as_date.year, as_date.month, as_date.day) self.assertEqual(as_date, date_sc) self.assertEqual(date_sc, as_date) # Ditto for datetimes. datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, as_date.day, 0, 0, 0) self.assertEqual(as_datetime, datetime_sc) self.assertEqual(datetime_sc, as_datetime)
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.assertTrue(not as_date == as_datetime) self.assertTrue(not as_datetime == as_date) self.assertRaises(TypeError, lambda: as_date < as_datetime) self.assertRaises(TypeError, lambda: as_datetime < as_date) self.assertRaises(TypeError, lambda: as_date <= as_datetime) self.assertRaises(TypeError, lambda: as_datetime <= as_date) self.assertRaises(TypeError, lambda: as_date > as_datetime) self.assertRaises(TypeError, lambda: as_datetime > as_date) self.assertRaises(TypeError, lambda: as_date >= as_datetime) self.assertRaises(TypeError, lambda: as_datetime >= as_date) # Neverthelss, comparison should work with the base-class (date) # projection if use of a date method is forced. self.assertTrue(as_date.__eq__(as_datetime)) different_day = (as_date.day + 1) % 20 + 1 self.assertTrue(not as_date.__eq__(as_datetime.replace(day= different_day))) # And date should compare with other subclasses of date. If a # subclass wants to stop this, it's up to the subclass to do so. date_sc = SubclassDate(as_date.year, as_date.month, as_date.day) self.assertEqual(as_date, date_sc) self.assertEqual(date_sc, as_date) # Ditto for datetimes. datetime_sc = SubclassDatetime(as_datetime.year, as_datetime.month, as_date.day, 0, 0, 0) self.assertEqual(as_datetime, datetime_sc) self.assertEqual(datetime_sc, as_datetime)
def test_tz_aware_arithmetic(self): import random now = self.theclass.now() tz55 = FixedOffset(-330, "west 5:30") timeaware = now.time().replace(tzinfo=tz55) nowaware = self.theclass.combine(now.date(), timeaware) self.assertIs(nowaware.tzinfo, tz55) self.assertEqual(nowaware.timetz(), timeaware) # Can't mix aware and non-aware. self.assertRaises(TypeError, lambda: now - nowaware) self.assertRaises(TypeError, lambda: nowaware - now) # And adding datetime's doesn't make sense, aware or not. self.assertRaises(TypeError, lambda: now + nowaware) self.assertRaises(TypeError, lambda: nowaware + now) self.assertRaises(TypeError, lambda: nowaware + nowaware) # Subtracting should yield 0. self.assertEqual(now - now, timedelta(0)) self.assertEqual(nowaware - nowaware, timedelta(0)) # Adding a delta should preserve tzinfo. delta = timedelta(weeks=1, minutes=12, microseconds=5678) nowawareplus = nowaware + delta self.assertIs(nowaware.tzinfo, tz55) nowawareplus2 = delta + nowaware self.assertIs(nowawareplus2.tzinfo, tz55) self.assertEqual(nowawareplus, nowawareplus2) # that - delta should be what we started with, and that - what we # started with should be delta. diff = nowawareplus - delta self.assertIs(diff.tzinfo, tz55) self.assertEqual(nowaware, diff) self.assertRaises(TypeError, lambda: delta - nowawareplus) self.assertEqual(nowawareplus - nowaware, delta) # Make up a random timezone. tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone") # Attach it to nowawareplus. nowawareplus = nowawareplus.replace(tzinfo=tzr) self.assertIs(nowawareplus.tzinfo, tzr) # Make sure the difference takes the timezone adjustments into account. got = nowaware - nowawareplus # Expected: (nowaware base - nowaware offset) - # (nowawareplus base - nowawareplus offset) = # (nowaware base - nowawareplus base) + # (nowawareplus offset - nowaware offset) = # -delta + nowawareplus offset - nowaware offset expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta self.assertEqual(got, expected) # Try max possible difference. min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min")) max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=FixedOffset(-1439, "max")) maxdiff = max - min self.assertEqual(maxdiff, self.theclass.max - self.theclass.min + timedelta(minutes=2*1439))
def test_tz_aware_arithmetic(self): import random now = self.theclass.now() tz55 = FixedOffset(-330, "west 5:30") timeaware = now.time().replace(tzinfo=tz55) nowaware = self.theclass.combine(now.date(), timeaware) self.assertTrue(nowaware.tzinfo is tz55) self.assertEqual(nowaware.timetz(), timeaware) # Can't mix aware and non-aware. self.assertRaises(TypeError, lambda: now - nowaware) self.assertRaises(TypeError, lambda: nowaware - now) # And adding datetime's doesn't make sense, aware or not. self.assertRaises(TypeError, lambda: now + nowaware) self.assertRaises(TypeError, lambda: nowaware + now) self.assertRaises(TypeError, lambda: nowaware + nowaware) # Subtracting should yield 0. self.assertEqual(now - now, timedelta(0)) self.assertEqual(nowaware - nowaware, timedelta(0)) # Adding a delta should preserve tzinfo. delta = timedelta(weeks=1, minutes=12, microseconds=5678) nowawareplus = nowaware + delta self.assertTrue(nowaware.tzinfo is tz55) nowawareplus2 = delta + nowaware self.assertTrue(nowawareplus2.tzinfo is tz55) self.assertEqual(nowawareplus, nowawareplus2) # that - delta should be what we started with, and that - what we # started with should be delta. diff = nowawareplus - delta self.assertTrue(diff.tzinfo is tz55) self.assertEqual(nowaware, diff) self.assertRaises(TypeError, lambda: delta - nowawareplus) self.assertEqual(nowawareplus - nowaware, delta) # Make up a random timezone. tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone") # Attach it to nowawareplus. nowawareplus = nowawareplus.replace(tzinfo=tzr) self.assertTrue(nowawareplus.tzinfo is tzr) # Make sure the difference takes the timezone adjustments into account. got = nowaware - nowawareplus # Expected: (nowaware base - nowaware offset) - # (nowawareplus base - nowawareplus offset) = # (nowaware base - nowawareplus base) + # (nowawareplus offset - nowaware offset) = # -delta + nowawareplus offset - nowaware offset expected = nowawareplus.utcoffset() - nowaware.utcoffset() - delta self.assertEqual(got, expected) # Try max possible difference. min = self.theclass(1, 1, 1, tzinfo=FixedOffset(1439, "min")) max = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=FixedOffset(-1439, "max")) maxdiff = max - min self.assertEqual(maxdiff, self.theclass.max - self.theclass.min + timedelta(minutes=2*1439))