本文整理汇总了Python中pytz.timezone函数的典型用法代码示例。如果您正苦于以下问题:Python timezone函数的具体用法?Python timezone怎么用?Python timezone使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了timezone函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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))
示例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
示例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
示例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)
示例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
示例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)
示例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'
)
示例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
示例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')
示例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
示例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()
示例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
示例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
示例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