我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用datetime.time.time()。
def __init__(self, options, columns): start_time = time.time() if (("keyspace" not in options) or ("columnfamily" not in options)) and ("query" not in options): logger.log("Either query or columnfamily and keyspace parameter is required.", ERROR) self.columnfamily = options.get("columnfamily", None) self.keyspace = options.get("keyspace", None) self.query = options.get("query", None) self.prepare_select_stmt = options.get("prepare_selects", properties.PREPARE_SELECTS_DEFAULT) == 'True' self.init_connection(options, columns) start_time1 = time.time() self.describe_db() end_time = time.time() self.insert_stmt = None self.delete_stmt = None self.prepared_select_stmts = {} if ISDEBUG: logger.log("DB described in {0} ms".format(int((end_time - start_time1) * 1000))) logger.log("initialized in {0} ms".format(int((end_time - start_time) * 1000)))
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)
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)
def test_easy(self): # Despite the name of this test, the endcases are excruciating. self.convert_between_tz_and_utc(Eastern, utc_real) self.convert_between_tz_and_utc(Pacific, utc_real) self.convert_between_tz_and_utc(Eastern, utc_fake) self.convert_between_tz_and_utc(Pacific, utc_fake) # The next is really dancing near the edge. It works because # Pacific and Eastern are far enough apart that their "problem # hours" don't overlap. self.convert_between_tz_and_utc(Eastern, Pacific) self.convert_between_tz_and_utc(Pacific, Eastern) # OTOH, these fail! Don't enable them. The difficulty is that # the edge case tests assume that every hour is representable in # the "utc" class. This is always true for a fixed-offset tzinfo # class (lke utc_real and utc_fake), but not for Eastern or Central. # For these adjacent DST-aware time zones, the range of time offsets # tested ends up creating hours in the one that aren't representable # in the other. For the same reason, we would see failures in the # Eastern vs Pacific tests too if we added 3*HOUR to the list of # offset deltas in convert_between_tz_and_utc(). # # self.convert_between_tz_and_utc(Eastern, Central) # can't work # self.convert_between_tz_and_utc(Central, Eastern) # can't work
def test_pickling_subclass(self): # Make sure we can pickle/unpickle an instance of a subclass. offset = timedelta(minutes=-300) orig = PicklableFixedOffset(offset, 'cookie') self.assertIsInstance(orig, tzinfo) self.assertTrue(type(orig) is PicklableFixedOffset) self.assertEqual(orig.utcoffset(None), offset) self.assertEqual(orig.tzname(None), 'cookie') for pickler, unpickler, proto in pickle_choices: green = pickler.dumps(orig, proto) derived = unpickler.loads(green) self.assertIsInstance(derived, tzinfo) self.assertTrue(type(derived) is PicklableFixedOffset) self.assertEqual(derived.utcoffset(None), offset) self.assertEqual(derived.tzname(None), 'cookie') ############################################################################# # Base class for testing a particular aspect of timedelta, time, date and # datetime comparisons.
def test_backdoor_resistance(self): # For fast unpickling, the constructor accepts a pickle string. # This is a low-overhead backdoor. A user can (by intent or # mistake) pass a string directly, which (if it's the right length) # will get treated like a pickle, and bypass the normal sanity # checks in the constructor. This can create insane objects. # The constructor doesn't want to burn the time to validate all # fields, but does check the month field. This stops, e.g., # datetime.datetime('1995-03-25') from yielding an insane object. base = '1995-03-25' if not issubclass(self.theclass, datetime): base = base[:4] for month_byte in '9', chr(0), chr(13), '\xff': self.assertRaises(TypeError, self.theclass, base[:2] + month_byte + base[3:]) for ord_byte in range(1, 13): # This shouldn't blow up because of the month byte alone. If # the implementation changes to do more-careful checking, it may # blow up because other fields are insane. self.theclass(base[:2] + chr(ord_byte) + base[3:]) ############################################################################# # datetime tests
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 fromtimestamp(timestamp, tz=None): """Return the local date and time corresponding to the POSIX timestamp. Same as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform's local date and time, and the returned datetime object is naive. Else tz must be an instance of a class tzinfo subclass, and the timestamp is converted to tz's time zone. In this case the result is equivalent to tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)). fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It's common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then it's possible to have two timestamps differing by a second that yield identical datetime objects. See also utcfromtimestamp(). """
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 self.assertRaises(TypeError, combine, d, "time") # wrong type self.assertRaises(TypeError, combine, "date", t) # wrong type
def today(): """Return the current local time. This is equivalent to date.fromtimestamp(time.time())"""
def fromtimestamp(timestamp): """Return the local date from a POSIX timestamp (like time.time()) This may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() function. It's common for this to be restricted to years from 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(). """
def timetuple(): """Return a 9-element tuple of the form returned by time.localtime(). The hours, minutes and seconds are 0, and the DST flag is -1. d.timetuple() is equivalent to (d.year, d.month, d.day, 0, 0, 0, d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1) """
def ctime(): """Return a string representing the date. For example date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())) on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard. """
def today(): """Return the current local datetime, with tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()). See also now(), fromtimestamp(). """
def utcnow(): """Return the current UTC date and time, with tzinfo None. This is like now(), but returns the current UTC date and time, as a naive datetime object. See also now(). """
def combine(date, time): """Return a new datetime object. Its date members are equal to the given date object's, and whose time and tzinfo members are equal to the given time object's. For any datetime object d, d == datetime.combine(d.date(), d.timetz()). If date is a datetime object, its time and tzinfo members are ignored. """
def time(): """Return time object with same hour, minute, second, microsecond. tzinfo is None. See also method timetz(). """
def timetz(): """Return time object with same hour, minute, second, microsecond, and tzinfo. See also method time(). """
def astimezone(tz): """Return a datetime object with new tzinfo member tz, adjusting the date and time members so the result is the same UTC time as self, but in tz's local time. tz must be an instance of a tzinfo subclass, and its utcoffset() and dst() methods must not return None. self must be aware (self.tzinfo must not be None, and self.utcoffset() must not return None). If self.tzinfo is tz, self.astimezone(tz) is equal to self: no adjustment of date or time members is performed. Else the result is local time in time zone tz, representing the same UTC time as self: after astz = dt.astimezone(tz), astz - astz.utcoffset() will usually have the same date and time members as dt - dt.utcoffset(). The discussion of class tzinfo explains the cases at Daylight Saving Time transition boundaries where this cannot be achieved (an issue only if tz models both standard and daylight time). If you merely want to attach a time zone object tz to a datetime dt without adjustment of date and time members, use dt.replace(tzinfo=tz). If you merely want to remove the time zone object from an aware datetime dt without conversion of date and time members, use dt.replace(tzinfo=None). Note that the default tzinfo.fromutc() method can be overridden in a tzinfo subclass to effect the result returned by astimezone(). """
def timetuple(): """Return a 9-element tuple of the form returned by time.localtime()."""
def utctimetuple(): """Return UTC time tuple compatilble with time.gmtimr()."""
def isoformat(sep='T'): """Return a string representing the date and time in ISO 8601 format. YYYY-MM-DDTHH:MM:SS.mmmmmm or YYYY-MM-DDTHH:MM:SS if microsecond is 0 If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or YYYY-MM-DDTHH:MM:SS+HH:MM if microsecond is 0. The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. """
def ctime(): """Return a string representing the date and time. datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'. d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())) on platforms where the native C ctime() function (which time.ctime() invokes, but which datetime.ctime() does not invoke) conforms to the C standard. """
def replace(hour, minute, second, microsecond, tzinfo): """Return a time with the same value. Except for those members given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive time from an aware time, without conversion of the time members. """
def isoformat(): """Return a string representing the time in ISO 8601 format. That is HH:MM:SS.mmmmmm or, if self.microsecond is 0, HH:MM:SS If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM """
def __str__(): """For a time t, str(t) is equivalent to t.isoformat()."""
def strftime(format): """Return a string representing the time. This is controlled by an explicit format string. """
def utcoffset(dt): """Return offset of local time from UTC, in minutes east of UTC. If local time is west of UTC, this should be negative. Note that this is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, utcoffset() should return their sum. If the UTC offset isn't known, return None. Else the value returned must be a timedelta object specifying a whole number of minutes in the range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset must be less than one day). """
def tzname(dt): """Return the time zone name corresponding to the datetime object as a string. """
def fromutc(dt): """Return an equivalent datetime in self's local time."""