本文整理汇总了Python中pytz.tz函数的典型用法代码示例。如果您正苦于以下问题:Python tz函数的具体用法?Python tz怎么用?Python tz使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tz函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_getitem_setitem_datetime_tz_dateutil
def test_getitem_setitem_datetime_tz_dateutil(self):
tm._skip_if_no_dateutil()
from dateutil.tz import tzutc
from pandas.tslib import _dateutil_gettz as gettz
tz = lambda x: tzutc() if x == 'UTC' else gettz(
x) # handle special case for utc in dateutil
from pandas import date_range
N = 50
# testing with timezone, GH #2785
rng = date_range('1/1/1990', periods=N, freq='H', tz='US/Eastern')
ts = Series(np.random.randn(N), index=rng)
# also test Timestamp tz handling, GH #2789
result = ts.copy()
result["1990-01-01 09:00:00+00:00"] = 0
result["1990-01-01 09:00:00+00:00"] = ts[4]
assert_series_equal(result, ts)
result = ts.copy()
result["1990-01-01 03:00:00-06:00"] = 0
result["1990-01-01 03:00:00-06:00"] = ts[4]
assert_series_equal(result, ts)
# repeat with datetimes
result = ts.copy()
result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = 0
result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = ts[4]
assert_series_equal(result, ts)
result = ts.copy()
result[datetime(1990, 1, 1, 3, tzinfo=tz('US/Central'))] = 0
result[datetime(1990, 1, 1, 3, tzinfo=tz('US/Central'))] = ts[4]
assert_series_equal(result, ts)
示例2: test_getitem_setitem_datetime_tz_pytz
def test_getitem_setitem_datetime_tz_pytz(self):
tm._skip_if_no_pytz()
from pytz import timezone as tz
from pandas import date_range
N = 50
# testing with timezone, GH #2785
rng = date_range('1/1/1990', periods=N, freq='H', tz='US/Eastern')
ts = Series(np.random.randn(N), index=rng)
# also test Timestamp tz handling, GH #2789
result = ts.copy()
result["1990-01-01 09:00:00+00:00"] = 0
result["1990-01-01 09:00:00+00:00"] = ts[4]
assert_series_equal(result, ts)
result = ts.copy()
result["1990-01-01 03:00:00-06:00"] = 0
result["1990-01-01 03:00:00-06:00"] = ts[4]
assert_series_equal(result, ts)
# repeat with datetimes
result = ts.copy()
result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = 0
result[datetime(1990, 1, 1, 9, tzinfo=tz('UTC'))] = ts[4]
assert_series_equal(result, ts)
result = ts.copy()
# comparison dates with datetime MUST be localized!
date = tz('US/Central').localize(datetime(1990, 1, 1, 3))
result[date] = 0
result[date] = ts[4]
assert_series_equal(result, ts)
示例3: add_event
def add_event(request):
username = request.user.username
form = NewEventForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
e_name = form.cleaned_data['e_name']
e_startdate = datetime.strptime(
form.cleaned_data['e_startdate'],
'%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei'))
e_enddate = datetime.strptime(
form.cleaned_data['e_enddate'],
'%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei'))
e_place = form.cleaned_data['e_place']
e_description = form.cleaned_data['e_description']
e_deadline = datetime.strptime(
form.cleaned_data['e_deadline'],
'%Y/%m/%d %I:%M %p').replace(tzinfo=tz('Asia/Taipei'))
event = Event.objects.create(
e_name=e_name,
e_startdate=e_startdate,
e_enddate=e_enddate,
e_place=e_place,
e_description=e_description,
e_deadline=e_deadline,
e_postdate=timezone.localtime(timezone.now()),
e_organizer=request.user)
participation = Participation.objects.create(
p_event=event,
p_member=event.e_organizer)
notification = Notification.objects.create(
n_from=User.objects.get(username='system'),
n_to=request.user,
n_timestamp=timezone.localtime(timezone.now()),
n_content='你已成功發佈了新活動:%s!\n\
活動詳情請<a href="/event_details?eventid=%d">按此</a>' % (
event.e_name, event.id))
return render(request, 'event_added.html', {'username': username,
'event': event})
else:
return render(request, 'add_event.html', {'username': username,
'form': form})
else:
form.initial['e_startdate'] = timezone.localtime(timezone.now(
)).strftime('%Y/%m/%d %I:%M %p')
form.initial['e_enddate'] = timezone.localtime(timezone.now(
)).strftime('%Y/%m/%d %I:%M %p')
form.initial['e_deadline'] = timezone.localtime(timezone.now(
)).strftime('%Y/%m/%d %I:%M %p')
return render(request, 'add_event.html', {'username': username,
'form': form})
示例4: __init__
def __init__(self, timezone, format = '%Y-(%m)%b-%d %T, %a w%V, %Z', sync_to = 1):
'''
Constructor
@param timezone:str The timezone
@param format:str The format as in the `date` command
@param sync_to:float The time parameter to sync to, the number of seconds between the reads
'''
self.utc = tz('UTC')
self.timezone = tz(timezone)
self.format = format
self.sync_to = sync_to
示例5: test_set_timezone
def test_set_timezone(self):
from .views import TimezoneView
from pytz import timezone as tz
request = self.factory.post("/abc", {"timezone": "America/Denver"})
self.add_session(request)
response = TimezoneView.as_view()(request)
self.assertEqual(response.status_code, 200)
self.assertIn("detected_timezone", request.session)
self.assertTrue(tz(request.session["detected_timezone"]))
temp = tz(request.session["detected_timezone"])
self.assertIsInstance(temp, BaseTzInfo)
示例6: check_attending_party
def check_attending_party(self):
current_time = timezone.now().astimezone(tz('US/Central'))
if self.attending:
if current_time > self.attending.time_end:
self.attending = None
self.save()
示例7: get_tonight_parties
def get_tonight_parties(self):
current_time = timezone.now().astimezone(tz('US/Central'))
tonight_begin = current_time - timedelta(hours=current_time.hour) + timedelta(hours=18)
tonight_end = current_time - timedelta(hours=current_time.hour) + timedelta(hours=30)
parties = self.get_all_related_parties()
return [party for party in parties if party.time_begin < tonight_end and party.time_end > tonight_begin]
示例8: test_effective
def test_effective(self):
self.news = create(Builder('news').within(self.newsfolder))
difference = datetime.now(tz('Europe/Zurich')) -\
self.news.effective().asdatetime()
# The folllowing Calculation is the same as timedelta.total_seconds()
# but since it isn't available in python2.6 we need to calculate it ourself
# https://docs.python.org/2/library/datetime.html#datetime.timedelta.total_seconds
self.assertLess((difference.microseconds +
(difference.seconds + difference.days * 24 * 3600)
* 10 ** 6) / 10.0 ** 6, 60)
示例9: clean
def clean(self):
startdate = datetime.strptime(self.cleaned_data['e_startdate'],
'%Y/%m/%d %I:%M %p')
startdate = startdate.replace(tzinfo=tz('Asia/Taipei'))
enddate = datetime.strptime(self.cleaned_data['e_enddate'],
'%Y/%m/%d %I:%M %p')
enddate = enddate.replace(tzinfo=tz('Asia/Taipei'))
deadline = datetime.strptime(self.cleaned_data['e_deadline'],
'%Y/%m/%d %I:%M %p')
deadline = deadline.replace(tzinfo=tz('Asia/Taipei'))
if timezone.localtime(timezone.now()) > startdate:
msg = '活動開始日期必須在今天之後!'
self.add_error('e_startdate', msg)
if timezone.localtime(timezone.now()) > deadline:
msg = '截止報名日期必須在今天之後!'
self.add_error('e_deadline', msg)
if timezone.localtime(timezone.now()) > enddate:
msg = '活動結束日期必須在今天之後!'
self.add_error('e_enddate', msg)
if deadline > startdate:
msg = '截止報名日期必須在活動開始日期之前!'
self.add_error('e_deadline', msg)
if startdate > enddate:
msg = '活動開始日期必須在結束日期之前!'
self.add_error('e_startdate', msg)
if enddate < startdate:
msg = '活動結束日期必須在開始日期之後!'
self.add_error('e_enddate', msg)
if enddate < deadline:
msg = '活動結束日期必須在截止報名日期之後!'
self.add_error('e_enddate', msg)
示例10: test_range_tz
def test_range_tz(self):
# GH 2906
_skip_if_no_pytz()
from pytz import timezone as tz
start = datetime(2011, 1, 1, tzinfo=tz('US/Eastern'))
end = datetime(2011, 1, 3, tzinfo=tz('US/Eastern'))
dr = date_range(start=start, periods=3)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
dr = date_range(end=end, periods=3)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
dr = date_range(start=start, end=end)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
示例11: run_server
def run_server(auction, mapping_expire_time, logger, timezone='Europe/Kiev'):
app.config.update(auction.worker_defaults)
# Replace Flask custom logger
app.logger_name = logger.name
app._logger = logger
app.config['auction'] = auction
app.config['timezone'] = tz(timezone)
app.config['SESSION_COOKIE_PATH'] = '/tenders/{}'.format(auction.auction_doc_id)
app.config['SESSION_COOKIE_NAME'] = 'auction_session'
app.oauth = OAuth(app)
app.remote_oauth = app.oauth.remote_app(
'remote',
consumer_key=app.config['OAUTH_CLIENT_ID'],
consumer_secret=app.config['OAUTH_CLIENT_SECRET'],
request_token_params={'scope': 'email'},
base_url=app.config['OAUTH_BASE_URL'],
access_token_url=app.config['OAUTH_ACCESS_TOKEN_URL'],
authorize_url=app.config['OAUTH_AUTHORIZE_URL']
)
@app.remote_oauth.tokengetter
def get_oauth_token():
return session.get('remote_oauth')
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = 'true'
# Start server on unused port
lisener = get_lisener(auction.worker_defaults["STARTS_PORT"],
host=auction.worker_defaults.get("WORKER_BIND_IP", ""))
app.logger.info(
"Start server on {0}:{1}".format(*lisener.getsockname()),
extra={"JOURNAL_REQUEST_ID": auction.request_id}
)
server = WSGIServer(lisener, app,
log=_LoggerStream(logger),
handler_class=AuctionsWSGIHandler)
server.start()
# Set mapping
mapping_value = "http://{0}:{1}/".format(*lisener.getsockname())
create_mapping(auction.worker_defaults["REDIS_URL"],
auction.auction_doc_id,
mapping_value)
app.logger.info("Server mapping: {} -> {}".format(
auction.auction_doc_id,
mapping_value,
mapping_expire_time
), extra={"JOURNAL_REQUEST_ID": auction.request_id})
# Spawn events functionality
spawn(push_timestamps_events, app,)
spawn(check_clients, app, )
return server
示例12: test_range_tz_dateutil
def test_range_tz_dateutil(self):
# GH 2906
tm._skip_if_no_dateutil()
# Use maybe_get_tz to fix filename in tz under dateutil.
from pandas.tslib import maybe_get_tz
tz = lambda x: maybe_get_tz('dateutil/' + x)
start = datetime(2011, 1, 1, tzinfo=tz('US/Eastern'))
end = datetime(2011, 1, 3, tzinfo=tz('US/Eastern'))
dr = date_range(start=start, periods=3)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
dr = date_range(end=end, periods=3)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
dr = date_range(start=start, end=end)
self.assert_(dr.tz == tz('US/Eastern'))
self.assert_(dr[0] == start)
self.assert_(dr[2] == end)
示例13: post
def post(self, request, *args, **kwargs):
timezone = request.POST.get("timezone", None)
if not timezone:
return HttpResponse("No 'timezone' parameter provided", status=400)
try:
if "none" in str(timezone).lower():
timezone = settings.TIME_ZONE
else:
timezone = str(timezone)
temp = tz(timezone)
except UnknownTimeZoneError:
return HttpResponse("Invalid 'timezone' value provided", status=400)
except:
return HttpResponse("An unknown error occurred while trying to parse the timezone", status=500)
request.session["detected_timezone"] = timezone
return HttpResponse(timezone, status=200)
示例14: _get_timezone
def _get_timezone(self, obj, change_type):
"""Ask the user to input an offset for a particular Dexcom G4 Platinum CGM device."""
res = input('What timezone were you in at %s? ' %(obj.user_time))
dst = input('Do you think this was a shift to/from DST? (y/n) ')
td_offset = tz(res).utcoffset(parse_datetime(obj.user_time))
offset = td_offset.days * 24 + td_offset.seconds/SECONDS_IN_HOUR
timezone = res
if dst == 'y':
change_type += '; shift to/from DST'
# fall back is -1; reverse it to undo change
if parse_datetime(obj.user_time).month > 6:
offset += 1
# spring forward is +1; reverse it to undo change
else:
offset -= 1
print('Offset from UTC is %d.' %offset)
print()
return (timezone, offset, change_type)
示例15: run
def run(self):
print('Running {} on PID {}'.format(self.name, self.pid))
while True:
# print(self.name)
worker_info = WorkerInfo.objects.get(name='NewWorker')
if worker_info.last_run < dt.now() - timedelta(hours=24):
with NewMatchScraper() as scraper:
new_matches_links = scraper.get_links()
print('Znaleziono {} nowych meczy'.format(len(new_matches_links)))
for link in new_matches_links:
new_match = Match()
with MatchPageScraper(link) as scraper:
match_info = scraper.get_match_info()
for key, value in match_info.items():
setattr(new_match, key, value)
new_match.bets.append(scraper.get_bets())
new_match.save()
print('Dodano nowy mecz: {}'.format(new_match.title))
worker_info.last_run = dt.now(tz('UTC'))
worker_info.save()
sleep(self.worker_delay)