我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用dateutil.tz.gettz()。
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 testFoldPositiveUTCOffset(self): # Test that we can resolve ambiguous times tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD0 = self.gettz(tzname) SYD1 = self.gettz(tzname) t0_u = datetime(2012, 3, 31, 15, 30, tzinfo=tz.tzutc()) # AEST t1_u = datetime(2012, 3, 31, 16, 30, tzinfo=tz.tzutc()) # AEDT # Using fresh tzfiles t0_syd0 = t0_u.astimezone(SYD0) t1_syd1 = t1_u.astimezone(SYD1) self.assertEqual(t0_syd0.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t1_syd1.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t0_syd0.utcoffset(), timedelta(hours=11)) self.assertEqual(t1_syd1.utcoffset(), timedelta(hours=10))
def testGapPositiveUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD0 = self.gettz(tzname) SYD1 = self.gettz(tzname) t0_u = datetime(2012, 10, 6, 15, 30, tzinfo=tz.tzutc()) # AEST t1_u = datetime(2012, 10, 6, 16, 30, tzinfo=tz.tzutc()) # AEDT # Using fresh tzfiles t0 = t0_u.astimezone(SYD0) t1 = t1_u.astimezone(SYD1) self.assertEqual(t0.replace(tzinfo=None), datetime(2012, 10, 7, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2012, 10, 7, 3, 30)) self.assertEqual(t0.utcoffset(), timedelta(hours=10)) self.assertEqual(t1.utcoffset(), timedelta(hours=11))
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 testEqualAmbiguousComparison(self): tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD0 = self.gettz(tzname) SYD1 = self.gettz(tzname) t0_u = datetime(2012, 3, 31, 14, 30, tzinfo=tz.tzutc()) # AEST t1_u = datetime(2012, 3, 31, 16, 30, tzinfo=tz.tzutc()) # AEDT t0_syd0 = t0_u.astimezone(SYD0) t0_syd1 = t0_u.astimezone(SYD1) # This is considered an "inter-zone comparison" because it's an # ambiguous datetime. self.assertEqual(t0_syd0, t0_syd1)
def mk_entry(): p = argparse.ArgumentParser(description="create a bark entry") p.add_argument("name", help="name of bark entry") p.add_argument("-a", "--attributes", action='append', type=lambda kv: kv.split("="), dest='keyvalues', help="extra metadata in the form of KEY=VALUE") p.add_argument("-t", "--timestamp", help="format: YYYY-MM-DD or YYYY-MM-DD_HH-MM-SS.S") p.add_argument("-p", "--parents", help="no error if already exists, new meta-data written", action="store_true") p.add_argument('--timezone', help="timezone of timestamp, default: America/Chicago", default='America/Chicago') args = p.parse_args() timestamp = arrow.get(args.timestamp).replace( tzinfo=tz.gettz(args.timezone)).datetime attrs = dict(args.keyvalues) if args.keyvalues else {} bark.create_entry(args.name, timestamp, args.parents, **attrs)
def convert_timestamp(engine, timestamp): """ Convert timezone from Zulu/UTC to the Engine's timezone engine: A Delphix engine session object. timestamp: the timstamp in Zulu/UTC to be converted """ default_tz = tz.gettz('UTC') engine_tz = time.time.get(engine) try: convert_tz = tz.gettz(engine_tz.system_time_zone) utc = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S') utc = utc.replace(tzinfo=default_tz) converted_tz = utc.astimezone(convert_tz) engine_local_tz = '{} {} {}'.format(str(converted_tz.date()), str(converted_tz.time()), str(converted_tz.tzname())) return engine_local_tz except TypeError: return None
def test_fields(self): time = datetime.now() entry = Entry('title', 'username', 'password', url='url', notes='notes', tags='tags', expires=True, expiry_time=time, icon=icons.KEY) self.assertEqual(entry.title, 'title') self.assertEqual(entry.username, 'username') self.assertEqual(entry.password, 'password') self.assertEqual(entry.url, 'url') self.assertEqual(entry.notes, 'notes') self.assertEqual(entry.tags, ['tags']) self.assertEqual(entry.expires, True) self.assertEqual(entry.expiry_time, time.replace(tzinfo=tz.gettz()).astimezone(tz.gettz('UTC'))) self.assertEqual(entry.icon, icons.KEY) self.assertEqual(entry.is_a_history_entry, False)
def my_local_time(): # METHOD 1: Hardcode zones: # from_zone = tz.gettz('UTC') # to_zone = tz.gettz('America/New_York') # METHOD 2: Auto-detect zones: from_zone = tz.tzutc() to_zone = tz.tzlocal() utc = datetime.utcnow() # utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S') # Tell the datetime object that it's in UTC time zone since # datetime objects are 'naive' by default utc = utc.replace(tzinfo=from_zone) # Convert time zone return utc.astimezone(to_zone)
def parse_timestamp(timestamp): if isinstance(timestamp, text_type): # HACK: Assume CET (Europe/Berlin) for human readable timestamp w/o timezone offset qualified = any([token in timestamp for token in ['Z', '+', ' CET', ' CEST']]) if not qualified: timestamp += ' CET' # Parse datetime string # Remark: Maybe use pandas.tseries.tools.parse_time_string? # TODO: Cache results of call to gettz to improve performance berlin = gettz('Europe/Berlin') tzinfos = {'CET': berlin, 'CEST': berlin} timestamp = parse(timestamp, tzinfos=tzinfos) return timestamp
def timezone(zone): """Try to get timezone using pytz or python-dateutil :param zone: timezone str :return: timezone tzinfo or None """ try: import pytz return pytz.timezone(zone) except ImportError: pass try: from dateutil.tz import gettz return gettz(zone) except ImportError: return None
def dashbaord(): ''' date = datetime.now() cnn = 'http://rss.cnn.com/rss/cnn_topstories.rss' news = feedparser.parse(cnn) feed = [] for item in news.get('items'): feed.append({'time':parser.parse(item['published']).astimezone(tz.gettz('America/Los_Angeles')).time().strftime("%I:%M %p"), 'title': item['title'], 'summary': item['summary_detail']['value'].split('<br')[0], 'link':item['links'][0]['href']}) allViews = getAllDevices() allDevices = allViews.get('all_devices') weather = allDevices.get('UUID123') forecast = weather.get('value').get('forecast') forecast = {'value':forecast} current=weather.get('value').get('current') alerts = weather.get('value').get('alerts') for item in forecast.get('value'): item['icon'] = WEATHER_MAPPING.get(item.get('icon')) current['icon'] = WEATHER_MAPPING.get(current.get('icon')) return render_template('dashboard.html', weather=forecast, current=current, alerts=alerts, date=date, feed=feed) ''' return render_template('ui.html')
def customize_parser (self, parser): parser.add_argument('--model', # type=get_model, choices=models.known.keys( )) parser.add_argument('--timezone', default=gettz( ), type=gettz, help="Timezone to use") parser.add_argument('--parser-out', dest="parsed_data", default='-', type=argparse.FileType('w'), help="Put history json in this file") return parser
def utcToLocal(dt): utc = tz.gettz('UTC') local = tz.tzlocal() dtUtc = dt.replace(tzinfo=utc) return dtUtc.astimezone(local)
def gen_tzinfos(): for zone in pytz.common_timezones: try: tzdate = pytz.timezone(zone).localize(dt.utcnow(), is_dst=None) except pytz.NonExistentTimeError: pass else: tzinfo = gettz(zone) if tzinfo: yield tzdate.tzname(), tzinfo
def pretty_print_datetime(dt): # Make sure the `dt` is timezone aware before pretty printing. if dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None: dt_pretty = dt.replace(tzinfo=tz.gettz('UTC')) dt_pretty = dt_pretty.astimezone(tz.tzlocal()) else: dt_pretty = dt.astimezone(tz.tzlocal()) dt_pretty_friendly = dt_pretty.strftime('%a %d %b, %I:%M%p') dt_pretty_humanized = humanize.naturaltime(dt_pretty.replace(tzinfo=None)) return '%s (%s)' % (dt_pretty_friendly, dt_pretty_humanized,)
def testZoneinfoStar(self): from dateutil.zoneinfo import gettz from dateutil.zoneinfo import gettz_db_metadata from dateutil.zoneinfo import rebuild zi_all = (gettz, gettz_db_metadata, rebuild) for var in zi_all: self.assertIsNot(var, None)
def gettz(self, tzname): raise NotImplementedError
def testFoldIndependence(self): tzname = self._get_tzname('America/New_York') with self._gettz_context(tzname): NYC = self.gettz(tzname) UTC = tz.tzutc() hour = timedelta(hours=1) # Firmly 2015-11-01 0:30 EDT-4 pre_dst = datetime(2015, 11, 1, 0, 30, tzinfo=NYC) # Currently, there's no way around the fact that this resolves to an # ambiguous date, which defaults to EST. I'm not hard-coding in the # answer, though, because the preferred behavior would be that this # results in a time on the EDT side. # Ambiguous between 2015-11-01 1:30 EDT-4 and 2015-11-01 1:30 EST-5 in_dst = pre_dst + hour in_dst_tzname_0 = in_dst.tzname() # Stash the tzname - EDT # Doing the arithmetic in UTC creates a date that is unambiguously # 2015-11-01 1:30 EDT-5 in_dst_via_utc = (pre_dst.astimezone(UTC) + 2*hour).astimezone(NYC) # Make sure the dates are actually ambiguous self.assertEqual(in_dst, in_dst_via_utc) # Make sure we got the right folding behavior self.assertNotEqual(in_dst_via_utc.tzname(), in_dst_tzname_0) # Now check to make sure in_dst's tzname hasn't changed self.assertEqual(in_dst_tzname_0, in_dst.tzname())
def _test_ambiguous_time(self, dt, tzid, ambiguous): # This is a test to check that the individual is_ambiguous values # on the _tzinfo subclasses work. tzname = self._get_tzname(tzid) with self._gettz_context(tzname): tzi = self.gettz(tzname) self.assertEqual(tz.datetime_ambiguous(dt, tz=tzi), ambiguous)
def _test_imaginary_time(self, dt, tzid, exists): tzname = self._get_tzname(tzid) with self._gettz_context(tzname): tzi = self.gettz(tzname) self.assertEqual(tz.datetime_exists(dt, tz=tzi), exists)
def testGettz(self): # bug 892569 str(self.gettz('UTC'))
def testGetTzEquality(self): self.assertEqual(self.gettz('UTC'), self.gettz('UTC'))
def testTimeOnlyGettz(self): # gettz returns None tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).utcoffset(), None)
def testTimeOnlyGettzDST(self): # gettz returns None tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).dst(), None)
def testTimeOnlyGettzTzName(self): tz_get = self.gettz('Europe/Minsk') self.assertIs(dt_time(13, 20, tzinfo=tz_get).tzname(), None)
def testPortugalDST(self): # In 1996, Portugal changed from CET to WET PORTUGAL = self.gettz('Portugal') t_cet = datetime(1996, 3, 31, 1, 59, tzinfo=PORTUGAL) self.assertEqual(t_cet.tzname(), 'CET') self.assertEqual(t_cet.utcoffset(), timedelta(hours=1)) self.assertEqual(t_cet.dst(), timedelta(0)) t_west = datetime(1996, 3, 31, 2, 1, tzinfo=PORTUGAL) self.assertEqual(t_west.tzname(), 'WEST') self.assertEqual(t_west.utcoffset(), timedelta(hours=1)) self.assertEqual(t_west.dst(), timedelta(hours=1))
def gettz(self, name): zoneinfo_file = zoneinfo.get_zonefile_instance() return zoneinfo_file.get(name)
def testZoneInfoFileStart1(self): tz = self.gettz("EST5EDT") self.assertEqual(datetime(2003, 4, 6, 1, 59, tzinfo=tz).tzname(), "EST", MISSING_TARBALL) self.assertEqual(datetime(2003, 4, 6, 2, 00, tzinfo=tz).tzname(), "EDT")
def testZoneInfoFileEnd1(self): tzc = self.gettz("EST5EDT") self.assertEqual(datetime(2003, 10, 26, 0, 59, tzinfo=tzc).tzname(), "EDT", MISSING_TARBALL) end_est = tz.enfold(datetime(2003, 10, 26, 1, 00, tzinfo=tzc), fold=1) self.assertEqual(end_est.tzname(), "EST")
def testZoneInfoOffsetSignal(self): utc = self.gettz("UTC") nyc = self.gettz("America/New_York") self.assertNotEqual(utc, None, MISSING_TARBALL) self.assertNotEqual(nyc, None) t0 = datetime(2007, 11, 4, 0, 30, tzinfo=nyc) t1 = t0.astimezone(utc) t2 = t1.astimezone(nyc) self.assertEqual(t0, t2) self.assertEqual(nyc.dst(t0), timedelta(hours=1))
def testZoneInfoDeepCopy(self): CHI = self.gettz('America/Chicago') CHI_COPY = copy.deepcopy(CHI) self.assertIsNot(CHI, CHI_COPY) self.assertEqual(CHI, CHI_COPY)
def testZoneInfoDeprecated(self): with self.assertWarns(DeprecationWarning): tzi = zoneinfo.gettz('US/Eastern')
def gettz(self, tzname): tzname_map = {'Australia/Sydney': self.TZ_AEST, 'America/Toronto': self.TZ_EST, 'America/New_York': self.TZ_EST} return tzname_map[tzname]
def testBrokenIsDstHandling(self): # tzrange._isdst() was using a date() rather than a datetime(). # Issue reported by Lennart Regebro. dt = datetime(2007, 8, 6, 4, 10, tzinfo=tz.tzutc()) self.assertEqual(dt.astimezone(tz=tz.gettz("GMT+2")), datetime(2007, 8, 6, 6, 10, tzinfo=tz.tzstr("GMT+2")))
def gettz(self, tzname): # Actual time zone changes are handled by the _gettz_context function tzname_map = {'Australia/Sydney': self.TZ_AEST, 'America/Toronto': self.TZ_EST, 'America/New_York': self.TZ_EST} return tz.tzstr(tzname_map[tzname])
def testGMTHasNoDaylight(self): # tz.tzstr("GMT+2") improperly considered daylight saving time. # Issue reported by Lennart Regebro. dt = datetime(2007, 8, 6, 4, 10) self.assertEqual(tz.gettz("GMT+2").dst(dt), timedelta(0))
def testGMTOffset(self): # GMT and UTC offsets have inverted signal when compared to the # usual TZ variable handling. dt = datetime(2007, 8, 6, 4, 10, tzinfo=tz.tzutc()) self.assertEqual(dt.astimezone(tz=tz.tzstr("GMT+2")), datetime(2007, 8, 6, 6, 10, tzinfo=tz.tzstr("GMT+2"))) self.assertEqual(dt.astimezone(tz=tz.gettz("UTC-2")), datetime(2007, 8, 6, 2, 10, tzinfo=tz.tzstr("UTC-2")))
def testPickleTzGettz(self): self.assertPicklable(tz.gettz('America/New_York'))
def testSupportAmbiguityFoldNaive(self): tzi = tz.gettz('US/Eastern') dt = datetime(2011, 11, 6, 1, 30) self.assertTrue(tz.datetime_ambiguous(dt, tz=tzi))
def testSupportAmbiguityFoldAware(self): tzi = tz.gettz('US/Eastern') dt = datetime(2011, 11, 6, 1, 30, tzinfo=tzi) self.assertTrue(tz.datetime_ambiguous(dt))
def testSupportAmbiguityUnambiguousNaive(self): tzi = tz.gettz('US/Eastern') dt = datetime(2011, 11, 6, 4, 30, tzinfo=tzi) self.assertFalse(tz.datetime_ambiguous(dt))
def testSpecifiedTzOverridesAttached(self): # If a tz is specified, the datetime will be treated as naive. # This is not ambiguous in the local zone dt = datetime(2011, 11, 6, 1, 30, tzinfo=tz.gettz('Australia/Sydney')) self.assertFalse(tz.datetime_ambiguous(dt)) tzi = tz.gettz('US/Eastern') self.assertTrue(tz.datetime_ambiguous(dt, tz=tzi))
def testInGapNaive(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 2, 30) self.assertFalse(tz.datetime_exists(dt, tz=tzi))
def testInGapAware(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 2, 30, tzinfo=tzi) self.assertFalse(tz.datetime_exists(dt))
def testExistsNaive(self): tzi = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 10, 30) self.assertTrue(tz.datetime_exists(dt, tz=tzi))
def testSpecifiedTzOverridesAttached(self): EST = tz.gettz('US/Eastern') AEST = tz.gettz('Australia/Sydney') dt = datetime(2012, 10, 7, 2, 30, tzinfo=EST) # This time exists self.assertFalse(tz.datetime_exists(dt, tz=AEST))
def rhd_filename_to_timestamp(fname, timezone): return arrow.get(fname, 'YYMMDD_HHmmss').replace( tzinfo=tz.gettz(timezone)).datetime