我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用dateutil.tz.tzfile()。
def testTzAll(self): from dateutil.tz import tzutc from dateutil.tz import tzoffset from dateutil.tz import tzlocal from dateutil.tz import tzfile from dateutil.tz import tzrange from dateutil.tz import tzstr from dateutil.tz import tzical from dateutil.tz import gettz from dateutil.tz import tzwin from dateutil.tz import tzwinlocal tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "gettz"] tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else [] lvars = locals() for var in tz_all: self.assertIsNot(lvars[var], None)
def testFoldNegativeUTCOffset(self): # Test that we can resolve ambiguous times tzname = self._get_tzname('America/Toronto') with self._gettz_context(tzname): # Calling fromutc() alters the tzfile object TOR0 = self.gettz(tzname) TOR1 = self.gettz(tzname) t0_u = datetime(2011, 11, 6, 5, 30, tzinfo=tz.tzutc()) t1_u = datetime(2011, 11, 6, 6, 30, tzinfo=tz.tzutc()) # Using fresh tzfiles t0_tor0 = t0_u.astimezone(TOR0) t1_tor1 = t1_u.astimezone(TOR1) self.assertEqual(t0_tor0.replace(tzinfo=None), datetime(2011, 11, 6, 1, 30)) self.assertEqual(t1_tor1.replace(tzinfo=None), datetime(2011, 11, 6, 1, 30)) self.assertEqual(t0_tor0.utcoffset(), timedelta(hours=-4.0)) self.assertEqual(t1_tor1.utcoffset(), timedelta(hours=-5.0))
def testGapNegativeUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('America/Toronto') with self._gettz_context(tzname): # Calling fromutc() alters the tzfile object TOR0 = self.gettz(tzname) TOR1 = self.gettz(tzname) t0_u = datetime(2011, 3, 13, 6, 30, tzinfo=tz.tzutc()) t1_u = datetime(2011, 3, 13, 7, 30, tzinfo=tz.tzutc()) # Using fresh tzfiles t0 = t0_u.astimezone(TOR0) t1 = t1_u.astimezone(TOR1) self.assertEqual(t0.replace(tzinfo=None), datetime(2011, 3, 13, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2011, 3, 13, 3, 30)) self.assertNotEqual(t0, t1) self.assertEqual(t0.utcoffset(), timedelta(hours=-5.0)) self.assertEqual(t1.utcoffset(), timedelta(hours=-4.0))
def testGapPositiveUTCOffset(self): # Test that we don't have a problem around gaps. tzname = 'AUS Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): # Calling fromutc() alters the tzfile object SYD = self.tzclass(*args) SYD0 = self.tzclass(*args) SYD1 = self.tzclass(*args) self.assertIsNot(SYD0, SYD1) t_n, t0_u, t1_u = self.get_utc_transitions(SYD, 2012, True) # Using fresh tzfiles t0 = t0_u.astimezone(SYD0) t1 = t1_u.astimezone(SYD1) self.assertEqual(t0.replace(tzinfo=None), t_n) self.assertEqual(t1.replace(tzinfo=None), t_n + timedelta(hours=2)) self.assertEqual(t0.utcoffset(), timedelta(hours=10)) self.assertEqual(t1.utcoffset(), timedelta(hours=11))
def testLeapCountDecodesProperly(self): # This timezone has leapcnt, and failed to decode until # Eugene Oden notified about the issue. # As leap information is currently unused (and unstored) by tzfile() we # can only indirectly test this: Take advantage of tzfile() not closing # the input file if handed in as an opened file and assert that the # full file content has been read by tzfile(). Note: For this test to # work NEW_YORK must be in TZif version 1 format i.e. no more data # after TZif v1 header + data has been read fileobj = BytesIO(base64.b64decode(NEW_YORK)) tzc = tz.tzfile(fileobj) # we expect no remaining file content now, i.e. zero-length; if there's # still data we haven't read the file format correctly remaining_tzfile_content = fileobj.read() self.assertEqual(len(remaining_tzfile_content), 0)
def gettz(name): tzinfo = None if ZONEINFOFILE: for cachedname, tzinfo in CACHE: if cachedname == name: break else: tf = TarFile.open(ZONEINFOFILE) try: zonefile = tf.extractfile(name) except KeyError: tzinfo = None else: tzinfo = tzfile(zonefile) tf.close() CACHE.insert(0, (name, tzinfo)) del CACHE[CACHESIZE:] return tzinfo
def __init__(self, zonefile_stream=None): if zonefile_stream is not None: with _tar_open(fileobj=zonefile_stream, mode='r') as tf: # dict comprehension does not work on python2.6 # TODO: get back to the nicer syntax when we ditch python2.6 # self.zones = {zf.name: tzfile(tf.extractfile(zf), # filename = zf.name) # for zf in tf.getmembers() if zf.isfile()} self.zones = dict((zf.name, tzfile(tf.extractfile(zf), filename=zf.name)) for zf in tf.getmembers() if zf.isfile()) # deal with links: They'll point to their parent object. Less # waste of memory # links = {zl.name: self.zones[zl.linkname] # for zl in tf.getmembers() if zl.islnk() or zl.issym()} links = dict((zl.name, self.zones[zl.linkname]) for zl in tf.getmembers() if zl.islnk() or zl.issym()) self.zones.update(links) else: self.zones = dict() # The current API has gettz as a module function, although in fact it taps into # a stateful class. So as a workaround for now, without changing the API, we # will create a new "global" class instance the first time a user requests a # timezone. Ugly, but adheres to the api. # # TODO: deprecate this.
def testFoldPositiveUTCOffset(self): # Test that we can resolve ambiguous times tzname = 'AUS Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): # Calling fromutc() alters the tzfile object SYD = self.tzclass(*args) SYD0 = self.tzclass(*args) SYD1 = self.tzclass(*args) self.assertIsNot(SYD0, SYD1) # Get the transition time in UTC from the object, because # Windows doesn't store historical info t_n, t0_u, t1_u = self.get_utc_transitions(SYD0, 2012, False) # Using fresh tzfiles t0_syd0 = t0_u.astimezone(SYD0) t1_syd1 = t1_u.astimezone(SYD1) self.assertEqual(t0_syd0.replace(tzinfo=None), t_n) self.assertEqual(t1_syd1.replace(tzinfo=None), t_n) self.assertNotEqual(t0_syd0, t1_syd1) self.assertEqual(t0_syd0.utcoffset(), timedelta(hours=11)) self.assertEqual(t1_syd1.utcoffset(), timedelta(hours=10)) # Re-using them across (make sure there's no cache problem) t0_syd1 = t0_u.astimezone(SYD1) t1_syd0 = t1_u.astimezone(SYD0) self.assertEqual(t0_syd0, t0_syd1) self.assertEqual(t1_syd1, t1_syd0)
def testGapNegativeUTCOffset(self): # Test that we don't have a problem around gaps. tzname = 'Eastern Standard Time' args = self.get_args(tzname) # Calling fromutc() alters the tzfile object with self.context(tzname): TOR = self.tzclass(*args) TOR0 = self.tzclass(*args) TOR1 = self.tzclass(*args) t_n, t0_u, t1_u = self.get_utc_transitions(TOR, 2011, True) # Using fresh tzfiles t0 = t0_u.astimezone(TOR0) t1 = t1_u.astimezone(TOR1) self.assertEqual(t0.replace(tzinfo=None), t_n) self.assertEqual(t1.replace(tzinfo=None), t_n + timedelta(hours=2)) self.assertNotEqual(t0, t1) self.assertEqual(t0.utcoffset(), timedelta(hours=-5.0)) self.assertEqual(t1.utcoffset(), timedelta(hours=-4.0))
def testFileStart1(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual(datetime(2003, 4, 6, 1, 59, tzinfo=tzc).tzname(), "EST") self.assertEqual(datetime(2003, 4, 6, 2, 00, tzinfo=tzc).tzname(), "EDT")
def testFileEnd1(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual(datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT") end_est = tz.enfold(datetime(2003, 10, 26, 1, 00, tzinfo=tzc)) self.assertEqual(end_est.tzname(), "EST")
def testFileLastTransition(self): # After the last transition, it goes to standard time in perpetuity tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertEqual(datetime(2037, 10, 25, 0, 59, tzinfo=tzc).tzname(), "EDT") last_date = tz.enfold(datetime(2037, 10, 25, 1, 00, tzinfo=tzc), fold=1) self.assertEqual(last_date.tzname(), "EST") self.assertEqual(datetime(2038, 5, 25, 12, 0, tzinfo=tzc).tzname(), "EST")
def testInvalidFile(self): # Should throw a ValueError if an invalid file is passed with self.assertRaises(ValueError): tz.tzfile(BytesIO(b'BadFile'))
def testIsStd(self): # NEW_YORK tzfile contains this isstd information: isstd_expected = (0, 0, 0, 1) tzc = tz.tzfile(BytesIO(base64.b64decode(NEW_YORK))) # gather the actual information as parsed by the tzfile class isstd = [] for ttinfo in tzc._ttinfo_list: # ttinfo objects contain boolean values isstd.append(int(ttinfo.isstd)) # ttinfo list may contain more entries than isstd file content isstd = tuple(isstd[:len(isstd_expected)]) self.assertEqual( isstd_expected, isstd, "isstd UTC/local indicators parsed: %s != tzfile contents: %s" % (isstd, isstd_expected))
def testPickleTzFileEST5EDT(self): tzc = tz.tzfile(BytesIO(base64.b64decode(TZFILE_EST5EDT))) self.assertPicklable(tzc)
def testPickleTzFileEurope_Helsinki(self): tzc = tz.tzfile(BytesIO(base64.b64decode(EUROPE_HELSINKI))) self.assertPicklable(tzc)
def testPickleTzFileNew_York(self): tzc = tz.tzfile(BytesIO(base64.b64decode(NEW_YORK))) self.assertPicklable(tzc)
def gettz(name): """ This retrieves a time zone from the local zoneinfo tarball that is packaged with dateutil. :param name: An IANA-style time zone name, as found in the zoneinfo file. :return: Returns a :class:`dateutil.tz.tzfile` time zone object. .. warning:: It is generally inadvisable to use this function, and it is only provided for API compatibility with earlier versions. This is *not* equivalent to ``dateutil.tz.gettz()``, which selects an appropriate time zone based on the inputs, favoring system zoneinfo. This is ONLY for accessing the dateutil-specific zoneinfo (which may be out of date compared to the system zoneinfo). .. deprecated:: 2.6 If you need to use a specific zoneinfofile over the system zoneinfo, instantiate a :class:`dateutil.zoneinfo.ZoneInfoFile` object and call :func:`dateutil.zoneinfo.ZoneInfoFile.get(name)` instead. Use :func:`get_zonefile_instance` to retrieve an instance of the dateutil-provided zoneinfo. """ warnings.warn("zoneinfo.gettz() will be removed in future versions, " "to use the dateutil-provided zoneinfo files, instantiate a " "ZoneInfoFile object and use ZoneInfoFile.zones.get() " "instead. See the documentation for details.", DeprecationWarning) if len(_CLASS_ZONE_INSTANCE) == 0: _CLASS_ZONE_INSTANCE.append(ZoneInfoFile(getzoneinfofile_stream())) return _CLASS_ZONE_INSTANCE[0].zones.get(name)
def __init__(self, zonefile_stream=None): if zonefile_stream is not None: with tar_open(fileobj=zonefile_stream, mode='r') as tf: # dict comprehension does not work on python2.6 # TODO: get back to the nicer syntax when we ditch python2.6 # self.zones = {zf.name: tzfile(tf.extractfile(zf), # filename = zf.name) # for zf in tf.getmembers() if zf.isfile()} self.zones = dict((zf.name, tzfile(tf.extractfile(zf), filename=zf.name)) for zf in tf.getmembers() if zf.isfile() and zf.name != METADATA_FN) # deal with links: They'll point to their parent object. Less # waste of memory # links = {zl.name: self.zones[zl.linkname] # for zl in tf.getmembers() if zl.islnk() or zl.issym()} links = dict((zl.name, self.zones[zl.linkname]) for zl in tf.getmembers() if zl.islnk() or zl.issym()) self.zones.update(links) try: metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) metadata_str = metadata_json.read().decode('UTF-8') self.metadata = json.loads(metadata_str) except KeyError: # no metadata in tar file self.metadata = None else: self.zones = dict() self.metadata = None
def __init__(self, zonefile_stream=None): if zonefile_stream is not None: with tar_open(fileobj=zonefile_stream, mode='r') as tf: # dict comprehension does not work on python2.6 # TODO: get back to the nicer syntax when we ditch python2.6 # self.zones = {zf.name: tzfile(tf.extractfile(zf), # filename = zf.name) # for zf in tf.getmembers() if zf.isfile()} self.zones = dict((zf.name, tzfile(tf.extractfile(zf), filename=zf.name)) for zf in tf.getmembers() if zf.isfile() and zf.name != METADATA_FN) # deal with links: They'll point to their parent object. Less # waste of memory # links = {zl.name: self.zones[zl.linkname] # for zl in tf.getmembers() if zl.islnk() or zl.issym()} links = dict((zl.name, self.zones[zl.linkname]) for zl in tf.getmembers() if zl.islnk() or zl.issym()) self.zones.update(links) try: metadata_json = tf.extractfile(tf.getmember(METADATA_FN)) metadata_str = metadata_json.read().decode('UTF-8') self.metadata = json.loads(metadata_str) except KeyError: # no metadata in tar file self.metadata = None else: self.zones = dict() self.metadata = None # The current API has gettz as a module function, although in fact it taps into # a stateful class. So as a workaround for now, without changing the API, we # will create a new "global" class instance the first time a user requests a # timezone. Ugly, but adheres to the api. # # TODO: deprecate this.