本文整理汇总了Python中pytz.tz函数的典型用法代码示例。如果您正苦于以下问题:Python tz函数的具体用法?Python tz怎么用?Python tz使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tz函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:8ballbb,项目名称:ProjectRothar,代码行数:35,代码来源:test_timeseries.py
示例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)
开发者ID:Alias4bb,项目名称:pandas,代码行数:35,代码来源:test_timeseries.py
示例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})
开发者ID:easontse,项目名称:DjangoLab,代码行数:54,代码来源:event.py
示例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
开发者ID:ViktorNova,项目名称:xpybar,代码行数:12,代码来源:tzclock.py
示例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)
开发者ID:BryanHurst,项目名称:timezone-detect,代码行数:13,代码来源:tests.py
示例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()
开发者ID:25cf,项目名称:party-on,代码行数:7,代码来源:models.py
示例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]
开发者ID:25cf,项目名称:party-on,代码行数:7,代码来源:models.py
示例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)
开发者ID:4teamwork,项目名称:ftw.contentpage,代码行数:10,代码来源:test_news_effective.py
示例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)
开发者ID:easontse,项目名称:DjangoLab,代码行数:40,代码来源:forms.py
示例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)
开发者ID:AjayRamanathan,项目名称:pandas,代码行数:22,代码来源:test_daterange.py
示例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
开发者ID:Leits,项目名称:openprocurement.auction,代码行数:51,代码来源:server.py
示例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)
开发者ID:ArbiterGames,项目名称:BasicPythonLinearRegression,代码行数:24,代码来源:test_daterange.py
示例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)
开发者ID:BryanHurst,项目名称:timezone-detect,代码行数:19,代码来源:views.py
示例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)
开发者ID:jasonbehrstock,项目名称:iPancreas-dexcom,代码行数:20,代码来源:convert_to_JSON.py
示例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)
开发者ID:akus5,项目名称:Webscraper,代码行数:21,代码来源:workers.py
示例16: happening
def happening(self):
current_time = timezone.now().astimezone(tz('US/Central'))
return self.time_begin < current_time and self.time_end > current_time
开发者ID:25cf,项目名称:party-on,代码行数:3,代码来源:models.py
示例17: download_file
def download_file(source_name, variable_name, out_path,
param_dict, start, end, session=None):
"""
Download a single file specified by ``param_dict``, ``start``, ``end``,
and save it to a directory constructed by combining ``source_name``,
``variable_name`` and ``out_path``. Returns None.
Parameters
----------
source_name : str
Name of source dataset, e.g. ``TenneT``
variable_name : str
Name of variable, e.g. ``solar``
out_path : str
Base download directory in which to save all downloaded files
param_dict : dict
Info required for download, e.g. url, url-parameter, filename.
start : datetime.date
start of data in the file
end : datetime.date
end of data in the file
session : requests.session, optional
If not given, a new session is created.
"""
if session is None:
session = requests.session()
logger.info(
'Downloading data:\n '
'Source: {}\n '
'Variable: {}\n '
'Data starts: {:%Y-%m-%d} \n '
'Data ends: {:%Y-%m-%d}'
.format(source_name, variable_name, start, end)
)
# Each file will be saved in a folder of its own, this allows us to preserve
# the original filename when saving to disk.
container = os.path.join(
out_path, source_name, variable_name,
start.strftime('%Y-%m-%d') + '_' +
end.strftime('%Y-%m-%d')
)
os.makedirs(container, exist_ok=True)
# Get number of months between now and start (required for TransnetBW).
count = (
datetime.now().month
- start.month
+ (datetime.now().year - start.year) * 12
)
if source_name == 'Elia':
start = tz('Europe/Brussels').localize(
datetime.combine(start, time())).astimezone(tz('UTC')
)
end = tz('Europe/Brussels').localize(
datetime.combine(end+timedelta(days=1), time())).astimezone(tz('UTC')
)
url_params = {} # A dict for paramters
# For most sources, we can use HTTP get method with paramters-dict
if param_dict['url_params_template']:
for key, value in param_dict['url_params_template'].items():
url_params[key] = value.format(
u_start=start,
u_end=end,
u_transnetbw=count
)
url = param_dict['url_template']
# For other sources that use urls without parameters (e.g. Svenska Kraftnaet)
else:
url = param_dict['url_template'].format(
u_start=start,
u_end=end,
u_transnetbw=count
)
# Attempt the download if there is no file yet.
count_files = len(os.listdir(container))
if count_files == 0:
resp = session.get(url, params=url_params)
# Get the original filename
try:
original_filename = (
resp.headers['content-disposition']
.split('filename=')[-1]
.replace('"', '')
.replace(';', '')
)
# For cases where the original filename can not be retrieved,
# I put the filename in the param_dict
except KeyError:
if 'filename' in param_dict:
original_filename = param_dict['filename'].format(u_start=start, u_end=end)
else:
logger.info(
#.........这里部分代码省略.........
开发者ID:JanUrb,项目名称:datapackage_timeseries,代码行数:101,代码来源:download.py
示例18: __init__
def __init__(self, timezone):
if not timezone:
raise NoTimezoneSet
self._timezone = tz(timezone)
self._datetime = datetime.now(self._timezone)
开发者ID:fathineos,项目名称:flask_base,代码行数:5,代码来源:date.py
示例19: make_auctions_app
def make_auctions_app(global_conf,
redis_url='redis://localhost:7777/0',
external_couch_url='http://localhost:5000/auction',
internal_couch_url='http://localhost:9000/',
proxy_internal_couch_url='http://localhost:9000/',
auctions_db='auctions',
hash_secret_key='',
timezone='Europe/Kiev',
preferred_url_scheme='http',
debug=False,
auto_build=False,
event_source_connection_limit=1000
):
"""
[app:main]
use = egg:openprocurement.auction#auctions_server
redis_url = redis://:[email protected]:1111/0
external_couch_url = http://localhost:1111/auction
internal_couch_url = http://localhost:9011/
auctions_db = auction
timezone = Europe/Kiev
"""
auctions_server.proxy_connection_pool = ConnectionPool(
factory=Connection, max_size=20, backend="gevent"
)
auctions_server.proxy_mappings = Memoizer({})
auctions_server.event_sources_pool = deque([])
auctions_server.config['PREFERRED_URL_SCHEME'] = preferred_url_scheme
auctions_server.config['REDIS_URL'] = redis_url
auctions_server.config['event_source_connection_limit'] = int(event_source_connection_limit)
auctions_server.config['EXT_COUCH_DB'] = urljoin(
external_couch_url,
auctions_db
)
auctions_server.add_url_rule(
'/' + auctions_db + '/<path:path>',
'couch_server_proxy',
couch_server_proxy,
methods=['GET'])
auctions_server.add_url_rule(
'/' + auctions_db + '/',
'couch_server_proxy',
couch_server_proxy,
methods=['GET'], defaults={'path': ''})
auctions_server.add_url_rule(
'/' + auctions_db + '_secured/<path:path>',
'auth_couch_server_proxy',
auth_couch_server_proxy,
methods=['GET'])
auctions_server.add_url_rule(
'/' + auctions_db + '_secured/',
'auth_couch_server_proxy',
auth_couch_server_proxy,
methods=['GET'], defaults={'path': ''})
auctions_server.config['INT_COUCH_URL'] = internal_couch_url
auctions_server.config['PROXY_COUCH_URL'] = proxy_internal_couch_url
auctions_server.config['COUCH_DB'] = auctions_db
auctions_server.config['TIMEZONE'] = tz(timezone)
auctions_server.redis = Redis(auctions_server)
auctions_server.db = Database(
urljoin(auctions_server.config.get('INT_COUCH_URL'),
auctions_server.config['COUCH_DB']),
session=Session(retry_delays=range(10))
)
auctions_server.config['HASH_SECRET_KEY'] = hash_secret_key
sync_design(auctions_server.db)
auctions_server.config['ASSETS_DEBUG'] = True if debug else False
assets.auto_build = True if auto_build else False
return auctions_server
开发者ID:VolVoz,项目名称:openprocurement.auction,代码行数:71,代码来源:auctions_server.py
示例20: update
def update(self):
self.data = self.model.objects(match_date__gte=dt.now(tz('UTC')) + timedelta(days=1))
print('Znaleziono {} meczy w tym tygodniu'.format(len(self.data)))
开发者ID:akus5,项目名称:Webscraper,代码行数:3,代码来源:workers.py
注:本文中的pytz.tz函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论