• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pytz.timezone函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pytz.timezone函数的典型用法代码示例。如果您正苦于以下问题:Python timezone函数的具体用法?Python timezone怎么用?Python timezone使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了timezone函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

 def __init__(self, lat=None, lon=None, tzname="UTC"):
     if lat is not None and lon is not None:
         with nostdout():
             w = tzwhere.tzwhere()
         self.tz = timezone(w.tzNameAt(lat, lon))
     else:
         self.tz = timezone(tzname)
开发者ID:imgrant,项目名称:fit2tcx,代码行数:7,代码来源:fit2tcx.py


示例2: now

 def now(self):
     """
     Returns a timezone aware datetime localized to the account's timezone.
     """
     now = datetime.datetime.utcnow().replace(tzinfo=pytz.timezone("UTC"))
     timezone = settings.TIME_ZONE if not self.timezone else self.timezone
     return now.astimezone(pytz.timezone(timezone))
开发者ID:bzeniti,项目名称:custom-djangouser-account,代码行数:7,代码来源:models.py


示例3: humanize

def humanize(obj, type=None, length=None):
    if obj is None:
        obj = ''
    elif type and type.startswith('time'):
        tz = type[len('time'):].lstrip('-')
        tz = timezone(tz) if tz else current_app.timezone or utc
        obj = format_time(float(obj), tz) if obj else ''
    elif type and type.startswith('natural-time'):
        tz = type[len('natural-time'):].lstrip('-')
        tz = timezone(tz) if tz else current_app.timezone or utc
        delta = datetime.now(tz) - datetime.fromtimestamp(float(obj), tz)
        if delta < timedelta(days=1):
            obj = format_timedelta(delta, locale='en_US') + ' ago'
        else:
            obj = format_time(float(obj), tz) if obj else ''
    elif isinstance(obj, string_types) and not re.match(UUID_REGEX, obj):
        obj = obj.replace('-', ' ').replace('_', ' ')
        obj = re.sub('|'.join(KEYWORDS_UP),
                     lambda m: m.group(0).upper(), obj)
        if obj and obj not in KEYWORDS_DOWN:
            obj = obj[0].upper() + obj[1:]
    elif isinstance(obj, list):
        if all(isinstance(x, (int, float) + string_types) for x in obj):
            obj = ', '.join(map(str, obj))
    if length is not None and len(obj) > length:
        obj = obj[:length - 4] + ' ...'
    return obj
开发者ID:117111302,项目名称:flower,代码行数:27,代码来源:template.py


示例4: convert_utc_to_user_timezone

def convert_utc_to_user_timezone(utc_timestamp):
	from pytz import timezone, UnknownTimeZoneError
	utcnow = timezone('UTC').localize(utc_timestamp)
	try:
		return utcnow.astimezone(timezone(get_user_time_zone()))
	except UnknownTimeZoneError:
		return utcnow
开发者ID:SILCORETECHNOLOGY,项目名称:frappe,代码行数:7,代码来源:data.py


示例5: remind

def remind(willie, trigger):
    """Gives you a reminder in the given amount of time."""
    duration = 0
    message = re.split('(\d+ ?(?:' + periods + ')) ?', trigger.group(2))[1:]
    reminder = ''
    stop = False
    for piece in message:
        grp = re.match('(\d+) ?(.*) ?', piece)
        if grp and not stop:
            length = float(grp.group(1))
            factor = scaling.get(grp.group(2), 60)
            duration += length * factor
        else:
            reminder = reminder + piece
            stop = True
    if duration == 0:
        return willie.reply("Sorry, didn't understand the input.")

    if duration % 1:
        duration = int(duration) + 1
    else:
        duration = int(duration)
    tzi = timezone('UTC')
    if willie.db and trigger.nick in willie.db.preferences:
        tz = willie.db.preferences.get(trigger.nick, 'tz') or 'UTC'
        tzi = timezone(tz)
    create_reminder(willie, trigger, duration, reminder, tzi)
开发者ID:astronouth7303,项目名称:willie,代码行数:27,代码来源:remind.py


示例6: get_passes

    def get_passes(self):


        passes_dict = []

        # use time of 4PM today for all calculations so that it always gets next rise and set times for this evening

        mytz = pytz.timezone(self.tz)
        eptz = pytz.timezone('utc')

        now = datetime.date.today()
        afternoon = mytz.localize( datetime.datetime(now.year,now.month,now.day)+ datetime.timedelta(hours=16))
        eptafternoon = afternoon.astimezone(eptz)
        # print "eptafternoon", eptafternoon

        # setup current location
        here = ephem.Observer()
        here.lon = str(self.lon)
        here.lat = str(self.lat)
        here.elev = self.alt
        here.date = eptafternoon
        # print here

        # do lookup from NASA website:
       
        url = params.nasa_url
        
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        data = response.read()

        # look for TWO LINE MEAN ELEMENT SET in file
        table = data.split("TWO LINE MEAN ELEMENT SET")[1]
        line1 = table.splitlines()[3]
        line2 = table.splitlines()[4]
        # print "line 1:", line1
        # print "line 2:", line2
        
        iss = ephem.readtle('ISS', \
                            line1, \
                            line2)


        # get next 5 passes, there would never be more than 5 passes after 4PM
        for apass in range(0,5):
            iss.compute(here)

            iss_np = here.next_pass(iss)
            iss_r = ephem.localtime(iss_np[0])
            iss_s = ephem.localtime(iss_np[4])
            # print "pass n: iss rise, set:", apass, iss_r, iss_s

        
            # Store the data in a list      
            passes_dict.append({"begin_time": iss_r, "end_time": iss_s})

            here.date = iss_np[4]
        
        # Return all the data     
        return passes_dict  
开发者ID:Nielsenfam,项目名称:NightSky,代码行数:60,代码来源:CreateISSInfoString.py


示例7: _add_dispatch_parameters

    def _add_dispatch_parameters(cls, func):

        # Force website with query string paramater, typically set from website selector in frontend navbar
        force_website_id = request.httprequest.args.get('fw')
        if (force_website_id and request.session.get('force_website_id') != force_website_id and
                request.env.user.has_group('website.group_multi_website') and
                request.env.user.has_group('website.group_website_publisher')):
            request.env['website']._force_website(request.httprequest.args.get('fw'))

        context = {}
        if not request.context.get('tz'):
            context['tz'] = request.session.get('geoip', {}).get('time_zone')
            try:
                pytz.timezone(context['tz'] or '')
            except pytz.UnknownTimeZoneError:
                context.pop('tz')

        request.website = request.env['website'].get_current_website()  # can use `request.env` since auth methods are called
        context['website_id'] = request.website.id
        # This is mainly to avoid access errors in website controllers where there is no
        # context (eg: /shop), and it's not going to propagate to the global context of the tab
        context['allowed_company_ids'] = [request.website.company_id.id]

        # modify bound context
        request.context = dict(request.context, **context)

        super(Http, cls)._add_dispatch_parameters(func)

        if request.routing_iteration == 1:
            request.website = request.website.with_context(request.context)
开发者ID:Vauxoo,项目名称:odoo,代码行数:30,代码来源:ir_http.py


示例8: test_timezone

 def test_timezone(self):
     dt = datetime(2009, 11, 10, 23, 0, 0, 123456)
     utc = UTC.localize(dt)
     berlin = timezone('Europe/Berlin').localize(dt)
     eastern = berlin.astimezone(timezone('US/Eastern'))
     data = {
         "points": [
             {"measurement": "A", "fields": {"val": 1},
              "time": 0},
             {"measurement": "A", "fields": {"val": 1},
              "time": "2009-11-10T23:00:00.123456Z"},
             {"measurement": "A", "fields": {"val": 1}, "time": dt},
             {"measurement": "A", "fields": {"val": 1}, "time": utc},
             {"measurement": "A", "fields": {"val": 1}, "time": berlin},
             {"measurement": "A", "fields": {"val": 1}, "time": eastern},
         ]
     }
     self.assertEqual(
         line_protocol.make_lines(data),
         '\n'.join([
             'A val=1i 0',
             'A val=1i 1257894000123456000',
             'A val=1i 1257894000123456000',
             'A val=1i 1257894000123456000',
             'A val=1i 1257890400123456000',
             'A val=1i 1257890400123456000',
         ]) + '\n'
     )
开发者ID:eman,项目名称:influxdb-python,代码行数:28,代码来源:test_line_protocol.py


示例9: make_utc_datetime

    def make_utc_datetime(**kwargs):
        """
        Helper function to convert the local (Chicago) time as scraped
        to a UTC datetime object.

        Expected in the kwargs:

        :param int year: Year of the concert start time.
        :param int month: Month of the concert start time.
        :param int day: Day of the concert start time.
        :param int hour: Hour of the concert start time.
        :param int minute: Minute of the concert start time.
        :returns: UTC datetime object.
        """

        naive_time_obj = datetime.datetime(
            year=kwargs['show_year'],
            month=kwargs['show_month'],
            day=kwargs['show_day'],
            hour=kwargs['show_hour'],
            minute=kwargs['show_minute'],
        )

        chicago_tz = pytz.timezone('US/Central')
        utc_tz = pytz.timezone('UTC')

        localized = chicago_tz.localize(naive_time_obj)
        utc_time = localized.astimezone(utc_tz)
        return utc_time
开发者ID:industryjhr,项目名称:sift_app,代码行数:29,代码来源:venue.py


示例10: check_uncheck_sampo

    def check_uncheck_sampo(self):
        action = self.request.GET.get('action')
        time = self.request.GET.get('time')

        if time:
            hhmm = map(lambda x: int(x), self.request.GET['time'].split(':'))
        else:
            hhmm = [0, 0]

        date_str = self.request.GET.get('date')

        if date_str:
            date = map(lambda x: int(x), date_str.split('.'))
            date_params = dict(
                zip(('day', 'month', 'year', 'hour', 'minute'), date+hhmm)
            )
            now = make_aware(datetime.datetime(**date_params), timezone(TIME_ZONE))
        else:
            now = make_aware(datetime.datetime.now(), timezone(TIME_ZONE)).replace(hour=hhmm[0], minute=hhmm[1], second=0, microsecond=0)

        if action == 'check':
            new_usage = SampoPassUsage(
                sampo_pass_id=int(self.request.GET['pid']),
                date=now
            )

            new_usage.save()

            passes, payments, _ = get_sampo_details(now)

            _json = json.dumps({
                'payments': payments
            })

            return HttpResponse(_json)

        elif action == 'uncheck':
            # todo Если админ системы удалит запись отсюда за любой день кроме сегоднешнего, удалится не та запись!
            # todo решать эту проблему лучше через передачу в функцию праильной даты...
            last_usage = SampoPassUsage.objects.filter(
                sampo_pass_id=int(self.request.GET['pid']),
                date__range=(
                    now.replace(hour=0, minute=0, second=0, microsecond=0),
                    now.replace(hour=23, minute=59, second=59, microsecond=999999)
                )
            ).last()

            if last_usage:
                last_usage.delete()

            passes, payments, _ = get_sampo_details(now)

            _json = json.dumps({
                'payments': payments
            })

            return HttpResponse(_json)

        else:
            return HttpResponseServerError('failed')
开发者ID:drda3x,项目名称:teacher_book,代码行数:60,代码来源:views.py


示例11: get_timezone

def get_timezone():
    """
    Returns the timezone that should be used for this request as
    `pytz.timezone` object.  This returns `None` if used outside of
    a request.
    """
    ctx = _request_ctx_stack.top
    tzinfo = getattr(ctx, 'babel_tzinfo', None)
    if tzinfo is None:
        babel = ctx.app.extensions['babel']
        if babel.timezone_selector_func is None:
            if not current_user.is_anonymous and current_user.timezone:
                tzinfo = timezone(current_user.timezone)
            elif current_website.company.timezone:
                tzinfo = timezone(current_website.company.timezone)
            else:
                tzinfo = babel.default_timezone
        else:
            rv = babel.timezone_selector_func()
            if rv is None:
                tzinfo = babel.default_timezone
            else:
                if isinstance(rv, basestring):
                    tzinfo = timezone(rv)
                else:
                    tzinfo = rv
        ctx.babel_tzinfo = tzinfo
    return tzinfo
开发者ID:fulfilio,项目名称:nereid,代码行数:28,代码来源:locale.py


示例12: make_plots

def make_plots(nc):
    ''' Generate some plots '''
    sts = compute_sts(nc)
    lats = nc.variables['lat'][:]
    lons = nc.variables['lon'][:]
    rts = (sts.astimezone(pytz.timezone("America/Chicago"))).strftime(
                                                            "%d %b %Y %H %p")
    for i, tm in enumerate(nc.variables['time'][:]):
        dt = sts + datetime.timedelta(minutes=float(tm))
        if dt.minute != 0:
            continue
        fhour = int( tm / 60.0 )
        fts = (dt.astimezone(pytz.timezone("America/Chicago"))).strftime(
                                                            "%d %b %Y %H %p")
        for pvar in PVARS:
            m = MapPlot(title='ISUMM5/Bridget Modelled %s' % (
                                                    PVARS[pvar]['title'],),
                        subtitle='Model Run: %s Forecast Valid: %s' % (rts, fts))
            vals = nc.variables[pvar][i,:,:]
            if pvar == 'bdeckt':
                vals = temperature(vals, 'K').value('F')
            m.pcolormesh(lons, lats, vals, PVARS[pvar]['levels'], units='mm')
            pqstr = "plot c %s model/frost/bridget/%02i/%s_%02i_f%03i.png bogus png" % (
                                        sts.strftime("%Y%m%d%H%M"), sts.hour,
                                        pvar, sts.hour, fhour)
            m.postprocess(pqstr=pqstr)
            m.close()
开发者ID:akrherz,项目名称:bridget,代码行数:27,代码来源:make_plots.py


示例13: __init__

    def __init__(self, *args, **kwargs):
        """Initialize form.

        Dynamically set choices for country field.
        """
        if 'editable_owner' in kwargs:
            self.editable_owner = kwargs['editable_owner']
            del(kwargs['editable_owner'])

        super(EventForm, self).__init__(*args, **kwargs)

        # Dynamic countries field.
        countries = product_details.get_regions('en').values()
        countries.sort()
        country_choices = ([('', "Country")] +
                           [(country, country) for country in countries])
        self.fields['country'].choices = country_choices

        # Dynamic owner field.
        if self.editable_owner:
            self.fields['owner_form'] = forms.ModelChoiceField(
                queryset=User.objects.filter(
                    userprofile__registration_complete=True,
                    groups__name='Rep'),
                empty_label='Owner', initial=self.instance.owner.pk)
        else:
            self.fields['owner_form'] = forms.CharField(
                required=False, initial=get_full_name(self.instance.owner),
                widget=forms.TextInput(attrs={'readonly': 'readonly',
                                              'class': 'input-text big'}))

        instance = self.instance
        # Dynamically set the year portion of the datetime widget
        now = datetime.now()
        start_year = getattr(self.instance.start, 'year', now.year)
        end_year = getattr(self.instance.end, 'year', now.year)
        self.fields['start_form'] = forms.DateTimeField(
            widget=SplitSelectDateTimeWidget(
                years=range(start_year, now.year + 10), minute_step=5),
            validators=[validate_datetime])
        self.fields['end_form'] = forms.DateTimeField(
            widget=SplitSelectDateTimeWidget(
                years=range(end_year, now.year + 10), minute_step=5),
            validators=[validate_datetime])
        # Make times local to venue
        if self.instance.start:
            start = make_naive(instance.local_start,
                               timezone(instance.timezone))
            self.fields['start_form'].initial = start

        if self.instance.end:
            end = make_naive(instance.local_end, timezone(instance.timezone))
            self.fields['end_form'].initial = end

        # Use of intermediate fields to translate between bug.id and
        # bug.bug_id
        if instance.budget_bug:
            self.fields['budget_bug_form'].initial = instance.budget_bug.bug_id
        if instance.swag_bug:
            self.fields['swag_bug_form'].initial = instance.swag_bug.bug_id
开发者ID:danyjavierb,项目名称:remo,代码行数:60,代码来源:forms.py


示例14: start_requests

    def start_requests(self):
        """
            default Scrapy method to send requests
        """

        # if spider already active
        if self.settings['active'] == 'T':
            log.msg('[OVERLAP] - at %s EST' % (datetime.now(timezone('US/Eastern')).strftime("%Y-%m-%d %H:%M:%S")), level=log.INFO)
            # Close the spider
            raise exceptions.CloseSpider('Recon Spider already active')

        # Set spider is activating
        ReconSpiderSettings(self.site).write_active('T')

        log.msg('[START_ID] - %s at %s EST' % (str(self.settings['recon_startid']), datetime.now(timezone('US/Eastern'))
                .strftime("%Y-%m-%d %H:%M:%S")), level=log.INFO)
        log.msg('[CYCLES] - %s at %s EST' % (
            str(self.settings['cycles']), datetime.now(timezone('US/Eastern')).strftime("%Y-%m-%d %H:%M:%S")), level=log.INFO)

        # requires a new recon_startid, if not, close the spider
        if self.settings['recon_startid'] == -1:
            # Close the spider and notice to provive initial start_id
            raise exceptions.CloseSpider('Provide start_id value via start_id parameter for initilizing')

        # Generate ids list for reconnoitering
        url_ids = generate_ids(self.site)
        
        # Send URL requests
        for id in url_ids:
            req = Request("".join((self.base_url, str(id))), dont_filter=True, callback=self.parse)
            # save url_id for calling back
            req.meta['url_id'] = id
            yield req
开发者ID:dayanstef,项目名称:cars_crawler,代码行数:33,代码来源:autotrader_recon.py


示例15: clean

    def clean(self):
        """Clean form."""
        super(EventForm, self).clean()

        cdata = self.cleaned_data

        cdata['budget_bug'] = cdata.get('budget_bug_form', None)
        cdata['swag_bug'] = cdata.get('swag_bug_form', None)
        if self.editable_owner:
            cdata['owner'] = cdata.get('owner_form', None)
        else:
            cdata['owner'] = self.instance.owner

        # Set timezone
        t = timezone(cdata['timezone'])
        if 'start_form' in cdata:
            start = make_naive(cdata['start_form'],
                               timezone(settings.TIME_ZONE))
            cdata['start'] = t.localize(start)

        if 'end_form' in cdata:
            end = make_naive(cdata['end_form'],
                             timezone(settings.TIME_ZONE))
            cdata['end'] = t.localize(end)

        # Directly write to self.errors as
        # ValidationError({'start_form': ['Error message']}) doesn't
        # seem to work.
        if cdata['start'] >= cdata['end']:
            self.errors['start_form'] = (u'Start date should come '
                                         'before end date.')
            raise ValidationError({'start_form': ['Error']})

        return cdata
开发者ID:shollmann,项目名称:remo,代码行数:34,代码来源:forms.py


示例16: test_simple_config

 def test_simple_config(self):
     config = get_config(PATH + 'simple.conf')
     comp_config = {
         'calendars': {
             'home': {'path': os.path.expanduser('~/.calendars/home/'),
                      'readonly': False, 'color': '', 'type': 'calendar'},
             'work': {'path': os.path.expanduser('~/.calendars/work/'),
                      'readonly': False, 'color': '', 'type': 'calendar'},
         },
         'sqlite': {'path': os.path.expanduser('~/.local/share/khal/khal.db')},
         'locale': {
             'local_timezone': pytz.timezone('Europe/Berlin'),
             'default_timezone': pytz.timezone('Europe/Berlin'),
             'timeformat': '%H:%M',
             'dateformat': '%d.%m.',
             'longdateformat': '%d.%m.%Y',
             'datetimeformat': '%d.%m. %H:%M',
             'longdatetimeformat': '%d.%m.%Y %H:%M',
             'firstweekday': 0,
             'encoding': 'utf-8',
             'unicode_symbols': True,
             'weeknumbers': False,
         },
         'default': {
             'default_command': 'calendar',
             'default_calendar': None,
             'show_all_days': False,
             'print_new': 'False',
             'days': 2,
         }
     }
     for key in comp_config:
         assert config[key] == comp_config[key]
开发者ID:0mark,项目名称:khal,代码行数:33,代码来源:settings_test.py


示例17: rss

def rss():
    items = []
    last_update_date = datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone('UTC'))
    now = datetime.now(tz=timezone('UTC'))

    for article_id, article_meta in articles_list.items():
        date = article_meta['published_time']

        if date > last_update_date:
            last_update_date = date

        func_name = 'article_by_id_en' if article_meta['locale'] == 'en' else 'article_by_id_de'

        meta = {
            'title': article_meta['title'],
            'url': url_for(func_name, article_id=article_id),
            'date': date,
        }

        # TODO filter for less days
        if (now - date).days <= 365:  # pragma: no cover
            items.append(meta)

    items = sorted(items, key=lambda item: item['date'], reverse=True)

    for item in items:
        item['date'] = item['date'].strftime('%a, %d %b %Y %H:%M:%S %z')

    resp = Response(render_template('rss.xml', items=items,
                                    last_update_date=last_update_date.strftime('%a, %d %b %Y %H:%M:%S %z')),
                    mimetype='application/rss+xml')
    return resp
开发者ID:berlin-leaks,项目名称:berlinleaks.org,代码行数:32,代码来源:app.py


示例18: testOldPickles

    def testOldPickles(self):
        # Ensure that applications serializing pytz instances as pickles
        # have no troubles upgrading to a new pytz release. These pickles
        # where created with pytz2006j
        east1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'US/Eastern'\np2\nI-18000\n"
            "I0\nS'EST'\np3\ntRp4\n."
            ))
        east2 = pytz.timezone('US/Eastern').localize(
            datetime(2006, 1, 1)).tzinfo
        self.assertTrue(east1 is east2)

        # Confirm changes in name munging between 2006j and 2007c cause
        # no problems.
        pap1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'America/Port_minus_au_minus_Prince'"
            "\np2\nI-17340\nI0\nS'PPMT'\np3\ntRp4\n."))
        pap2 = pytz.timezone('America/Port-au-Prince').localize(
            datetime(1910, 1, 1)).tzinfo
        self.assertTrue(pap1 is pap2)

        gmt1 = pickle.loads(_byte_string(
            "cpytz\n_p\np1\n(S'Etc/GMT_plus_10'\np2\ntRp3\n."))
        gmt2 = pytz.timezone('Etc/GMT+10')
        self.assertTrue(gmt1 is gmt2)
开发者ID:imasahiro,项目名称:sphinx-maven-plugin,代码行数:25,代码来源:test_tzinfo.py


示例19: utc_timestamp

def utc_timestamp(cr, uid, timestamp, context=None):
    """Returns the given timestamp converted to the client's timezone.
       This method is *not* meant for use as a _defaults initializer,
       because datetime fields are automatically converted upon
       display on client side. For _defaults you :meth:`fields.datetime.now`
       should be used instead.

       :param datetime timestamp: naive datetime value (expressed in LOCAL)
                                  to be converted to the client timezone
       :param dict context: the 'tz' key in the context should give the
                            name of the User/Client timezone (otherwise
                            UTC is used)
       :rtype: datetime
       :return: timestamp converted to timezone-aware datetime in UTC
    """
    assert isinstance(timestamp, datetime), 'Datetime instance expected'
    if context and context.get('tz'):
        tz_name = context['tz']  
    else:
        registry = RegistryManager.get(cr.dbname)
        tz_name = registry.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
    if tz_name:
        try:
            utc = pytz.timezone('UTC')
            context_tz = pytz.timezone(tz_name)
            context_timestamp = context_tz.localize(timestamp, is_dst=False) # UTC = no DST
            return context_timestamp.astimezone(utc)
        except Exception:
            _logger.debug("failed to compute context/client-specific timestamp, "
                          "using the UTC value",
                          exc_info=True)
    return timestamp
开发者ID:hoangtk,项目名称:metro-test,代码行数:32,代码来源:utils.py


示例20: testPeopleRants

  def testPeopleRants(self):
    """This test contains various things which people rant about."""

    # Tests some of the pitfuls discussed at
    # http://www.enricozini.org/2009/debian/using-python-datetime/
    ############################################################################

    # That's right, the datetime object created by a call to datetime.datetime
    # constructor now seems to think that Finland uses the ancient "Helsinki
    # Mean Time" which was obsoleted in the 1920s.
    #
    # Well not anymore!
    eurhel = pytz.timezone("Europe/Helsinki")
    a = datetime_tz.datetime_tz(2008, 6, 23, 18, 2, 31, 101025, eurhel)
    self.assertEqual(repr(a),
                     "datetime_tz(2008, 6, 23, 18, 2, 31, 101025,"
                     " tzinfo=<DstTzInfo 'Europe/Helsinki' EEST+3:00:00 DST>)")

    # Timezone-aware datetime objects have other bugs: for example, they fail to
    # compute Unix timestamps correctly. The following example shows two
    # timezone-aware objects that represent the same instant but produce two
    # different timestamps.
    #
    # Well not anymore!
    utc = pytz.timezone("UTC")
    a = datetime_tz.datetime_tz(2008, 7, 6, 5, 4, 3, tzinfo=utc)
    self.assertEqual(str(a), "2008-07-06 05:04:03+00:00")
    self.assertEqual(a.totimestamp(), 1215320643.0)
    # FIXME(tansell): %s is effected by the TZ environment value.
    #self.assertEqual(a.strftime("%s"), "1215284643")

    italy = pytz.timezone("Europe/Rome")
    b = a.astimezone(italy)
    self.assertEqual(str(b), "2008-07-06 07:04:03+02:00")
    self.assertEqual(b.totimestamp(), 1215320643.0)
开发者ID:jamezpolley,项目名称:python-datetime-tz,代码行数:35,代码来源:tests.py



注:本文中的pytz.timezone函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pytz.tz函数代码示例发布时间:2022-05-27
下一篇:
Python pytz.country_timezones函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap