python类gettz()的实例源码

test_imports.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 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))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 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)
barkutils.py 文件源码 项目:bark 作者: kylerbrown 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
GetReferences.py 文件源码 项目:delphixpy-examples 作者: CloudSurgeon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
tests.py 文件源码 项目:pykeepass 作者: pschmitt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
main.py 文件源码 项目:EasyCrawler 作者: playwolf719 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
util.py 文件源码 项目:kotori 作者: daq-tools 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:oejia_wx 作者: JoneXiong 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:TornadoWeb 作者: VxCoder 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
web_ui.py 文件源码 项目:Firefly 作者: Firefly-Automation 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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')
mm-history.py 文件源码 项目:decocare 作者: openaps 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
mm-glucose.py 文件源码 项目:decocare 作者: openaps 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
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
tools.py 文件源码 项目:whatsapp-rest-webservice 作者: svub 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def utcToLocal(dt):
        utc = tz.gettz('UTC')
        local = tz.tzlocal()
        dtUtc =  dt.replace(tzinfo=utc)

        return dtUtc.astimezone(local)
dates.py 文件源码 项目:riko 作者: nerevu 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
time.py 文件源码 项目:mimiron 作者: ImageIntelligence 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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,)
test_imports.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def gettz(self, tzname):
        raise NotImplementedError
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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())
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def testGettz(self):
        # bug 892569
        str(self.gettz('UTC'))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def testGetTzEquality(self):
        self.assertEqual(self.gettz('UTC'), self.gettz('UTC'))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def testTimeOnlyGettz(self):
        # gettz returns None
        tz_get = self.gettz('Europe/Minsk')
        self.assertIs(dt_time(13, 20, tzinfo=tz_get).utcoffset(), None)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def testTimeOnlyGettzDST(self):
        # gettz returns None
        tz_get = self.gettz('Europe/Minsk')
        self.assertIs(dt_time(13, 20, tzinfo=tz_get).dst(), None)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def testTimeOnlyGettzTzName(self):
        tz_get = self.gettz('Europe/Minsk')
        self.assertIs(dt_time(13, 20, tzinfo=tz_get).tzname(), None)
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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))
test_tz.py 文件源码 项目:Dshield 作者: ywjt 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def gettz(self, name):
        zoneinfo_file = zoneinfo.get_zonefile_instance()
        return zoneinfo_file.get(name)


问题


面经


文章

微信
公众号

扫码关注公众号