本文整理汇总了Python中pytz.utc.localize函数的典型用法代码示例。如果您正苦于以下问题:Python localize函数的具体用法?Python localize怎么用?Python localize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了localize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_coreitemvalues
def test_coreitemvalues(self):
self.assertEquals(self.item.get('type'), 'text')
self.assertEquals(self.item.get('urgency'), 4)
self.assertEquals(self.item.get('version'), '1')
self.assertEquals(self.item.get('versioncreated'), utc.localize(datetime.datetime(2014, 8, 29, 13, 49, 51)))
self.assertEquals(self.item.get('firstcreated'), utc.localize(datetime.datetime(2014, 8, 29, 13, 49, 51)))
self.assertEquals(self.item.get('pubstatus'), 'usable')
开发者ID:jerome-poisson,项目名称:superdesk-core,代码行数:7,代码来源:afp_tests.py
示例2: update_from_facebook
def update_from_facebook():
resp = requests.get('https://graph.facebook.com/207150099413259/feed',
params={'access_token':
app.config['FACEBOOK_ACCESS_TOKEN']})
if 200 <= resp.status_code < 400:
posts = resp.json()['data']
while posts:
latest_post = posts.pop(0)
if 'open' in latest_post['message'].lower() or 'close' in latest_post['message'].lower():
break
latest_post['created_time'] = utc.localize(datetime.strptime(
latest_post['created_time'], '%Y-%m-%dT%H:%M:%S+0000'))
else:
return False
latest_db_record = Call.query.order_by(Call.date.desc()).first()
if latest_db_record.date > latest_post['created_time']:
return True
if latest_db_record and latest_post['id'] == latest_db_record.id:
utcnow = utc.localize(datetime.utcnow())
since_update = utcnow - latest_db_record.date
eastern_hr = utcnow.astimezone(timezone('US/Eastern')).hour
if 9 <= eastern_hr < 18:
# 12 hr grace period if after 9AM, but before usual closing time
return since_update < timedelta(hours=12)
else:
# 24 hr grace period if before 9AM (or after closing)
return since_update < timedelta(hours=24)
db.session.add(Call(id=latest_post['id'],
recording_url='https://facebook.com/' + latest_post['id'],
transcript=latest_post['message'],
date=latest_post['created_time']))
db.session.commit()
return True
开发者ID:dschep,项目名称:fountainhead-status,代码行数:34,代码来源:fountainheadstatus.py
示例3: ics
def ics(group):
locale.setlocale(locale.LC_ALL, 'fr_FR.utf8')
login, pw = read_credentials()
request = requests.get(
'https://edt.univ-nantes.fr/sciences/' + group + '.ics',
auth=(login, pw))
if not 200 <= request.status_code < 300:
return "Error status while retrieving the ics file."
format = "%Y%m%dT%H%M%SZ"
now = datetime.utcnow().strftime(format)
paris = pytz.timezone('Europe/Paris')
current = '99991231T235959Z'
dtstart = dtend = description = ''
for component in Calendar.from_ical(request.text).walk():
if component.name == 'VEVENT':
current_start = component.get('DTSTART').to_ical()
if now > current_start:
continue
if current_start < current:
current = current_start
description = unicode(component.get('DESCRIPTION'))
start = component.get('DTSTART').to_ical()
end = component.get('DTEND').to_ical()
dtutcstart = utc.localize(datetime.strptime(start, format))
dtutcend = utc.localize(datetime.strptime(end, format))
dtstart = dtutcstart.astimezone(paris)
dtend = dtutcend.astimezone(paris)
result = (u"Prochain cours le {date} de {start} à {end} :\n"
"{description}").format(
date=dtstart.strftime("%A %d/%m/%Y"),
start=dtstart.strftime("%Hh%M"),
end=dtend.strftime("%Hh%M"),
description=description).encode('utf8').strip()
return result
开发者ID:AtalM2,项目名称:atalatchatche,代码行数:34,代码来源:ics.py
示例4: extract_mail
def extract_mail(**mail):
agent = mail['from']
if agent == '[email protected]':
subject = mail['subject']
content = mail['plain']
data = content_extractor(content)
if data['account'] == '0113011666':
if subject.find('Credit') != -1:
try:
obj = Wallet.objects.get(walletID=data['walletID'])
obj.amount = obj.amount + data['amount']
obj.datetime = utc.localize(datetime.datetime.strptime(data['date']+" "+data['time'], '%d-%b-%Y %I:%M%p'))
obj.ack = True
obj.save()
wall = WalletLog(wallet=obj, amount=data['amount'], datetime=utc.localize(datetime.datetime.utcnow()), report='savings')
wall.save()
except Wallet.DoesNotExist:
return HttpResponseNotFound()
elif subject.find('Debit') != -1:
return HttpResponseNotFound()
else:
return HttpResponseNotFound()
else:
return HttpResponseNotFound()
开发者ID:Chitrank-Dixit,项目名称:kibati-arooko,代码行数:31,代码来源:utils.py
示例5: test_calculate_pass_slot
def test_calculate_pass_slot(self):
"""UNIT test: services.common.simualtion.trigger_event
Validates the calculation of the pass slots that occur during an
availability slot.
"""
# ### TODO Understand inaccuracies in between PyEphem and GPredict
# ### TODO when the minimum contact elevation angle increases,
# ### TODO what is the influence of body.compute(observer) within the
# ### TODO simulation loop?
if self.__verbose_testing:
print('>>> test_calculate_pass_slot:')
self.__simulator.set_groundstation(self.__gs_1)
self.__simulator.set_spacecraft(
tle_models.TwoLineElement.objects.get(identifier=self.__sc_1_tle_id)
)
if self.__verbose_testing:
print(self.__simulator.__unicode__())
pass_slots = self.__simulator.calculate_pass_slot(
start=pytz_utc.localize(datetime.today()),
end=pytz_utc.localize(datetime.today()) + timedelta(days=3)
)
if self.__verbose_testing:
print('# ### RESULTS:')
for p in pass_slots:
print('[' + str(p[0]) + ', ' + str(p[1]) + ']')
开发者ID:satnet-project,项目名称:server,代码行数:29,代码来源:test_simulation.py
示例6: setUp
def setUp(self):
self.calendar = Calendar.objects.create(name='Calendar', is_active=True)
self.recurrences = recurrence.Recurrence(
rrules=[recurrence.Rule(recurrence.WEEKLY, until=utc.localize(datetime.datetime(2014, 1, 31)))])
programme = Programme.objects.filter(name="Classic hits").get()
programme.name = "Classic hits 2"
programme.slug = None
programme.id = programme.pk = None
programme.save()
self.programme = programme
self.schedule = Schedule.objects.create(
programme=self.programme,
type='L',
recurrences=self.recurrences,
start_dt=utc.localize(datetime.datetime(2014, 1, 6, 14, 0, 0)),
calendar=self.calendar)
self.episode = Episode.objects.create(
title='Episode 1',
programme=programme,
summary='',
season=1,
number_in_season=1,
)
self.programme.rearrange_episodes(pytz.utc.localize(datetime.datetime(1970, 1, 1)), Calendar.get_active())
self.episode.refresh_from_db()
开发者ID:iago1460,项目名称:django-radio,代码行数:29,代码来源:test_schedules.py
示例7: test_add_to_log
def test_add_to_log(tmpdir):
logs = [
FoodLog(
utc.localize(datetime.datetime.utcnow()),
1,
5,
['sleepy', 'hungry'],
['broccoli'],
['test'],
SNACK,
""
),
FoodLog(
utc.localize(datetime.datetime.utcnow()),
5,
2,
['happy'],
['popcorn', 'butter'],
['movies', 'test'],
SNACK,
"I am a note"
)
]
log_file = str(tmpdir.join("log.txt"))
for l in logs:
add_log_to_file(log_file, l)
with open(log_file, 'r') as infile:
results = [json_to_food_log(l) for l in infile]
assert logs == results
开发者ID:Bachmann1234,项目名称:journaler,代码行数:29,代码来源:test_load.py
示例8: order
def order(group):
global request
if request == "":
request = connect(group) # objet reçu de la connexion via la
# fonction connect définie plus bas.
paris = pytz.timezone('Europe/Paris')
format = "%Y%m%dT%H%M%SZ"
datefind = datetime(2014, 4, 16, 11) # careful: 04 is invalid. 4
# is. (octal numbers not allowed in python!)
find = datefind.strftime("%d/%m/%Y/%Hh%M")
ffind = utc.localize(datefind)
fffind = ffind.astimezone(paris)
#semaine de 4 à 22 (19 semaine)
#semaine de 6 jour
#jour de 8 crénaux
#tableau de 19 * 6 * 8 = 912 case
crenaux = [1]*912
for component in Calendar.from_ical(request.text).walk():
if component.name == 'VEVENT':
start = component.get('DTSTART').to_ical()
dtutcstart = utc.localize(datetime.strptime(start, format))
dtstart = dtutcstart.astimezone(paris)
fstart = dtstart.strftime("%d/%m/%Y/%Hh%M")
end = component.get('DTEND').to_ical()
dtutcend = utc.localize(datetime.strptime(end, format))
dtend = dtutcend.astimezone(paris)
fend = dtend.strftime("%d/%m/%Y/%Hh%M")
getCrenaux(crenaux, dtstart, dtend)
return crenaux
开发者ID:sildar,项目名称:Edt_Analyser,代码行数:35,代码来源:edt_analyser.py
示例9: handle
def handle(self, *args, **options):
course_keys = None
modified_start = None
modified_end = None
run_mode = get_mutually_exclusive_required_option(options, 'delete', 'dry_run')
courses_mode = get_mutually_exclusive_required_option(options, 'courses', 'all_courses')
db_table = options.get('db_table')
if db_table not in {'subsection', 'course', None}:
raise CommandError('Invalid value for db_table. Valid options are "subsection" or "course" only.')
if options.get('modified_start'):
modified_start = utc.localize(datetime.strptime(options['modified_start'], DATE_FORMAT))
if options.get('modified_end'):
if not modified_start:
raise CommandError('Optional value for modified_end provided without a value for modified_start.')
modified_end = utc.localize(datetime.strptime(options['modified_end'], DATE_FORMAT))
if courses_mode == 'courses':
course_keys = parse_course_keys(options['courses'])
log.info("reset_grade: Started in %s mode!", run_mode)
operation = self._query_grades if run_mode == 'dry_run' else self._delete_grades
if db_table == 'subsection' or db_table is None:
operation(PersistentSubsectionGrade, course_keys, modified_start, modified_end)
if db_table == 'course' or db_table is None:
operation(PersistentCourseGrade, course_keys, modified_start, modified_end)
log.info("reset_grade: Finished in %s mode!", run_mode)
开发者ID:shevious,项目名称:edx-platform,代码行数:33,代码来源:reset_grades.py
示例10: check_results
def check_results(self, holiday, start, end, expected):
assert list(holiday.dates(start, end)) == expected
# Verify that timezone info is preserved.
assert (list(holiday.dates(utc.localize(Timestamp(start)),
utc.localize(Timestamp(end)))) ==
[utc.localize(dt) for dt in expected])
开发者ID:DusanMilunovic,项目名称:pandas,代码行数:7,代码来源:test_holiday.py
示例11: test_save_rearrange_episodes
def test_save_rearrange_episodes(self):
self.assertEqual(self.episode.issue_date, utc.localize(datetime.datetime(2014, 1, 6, 14, 0, 0)))
self.episode.issue_date = None
self.episode.save()
self.schedule.save()
self.episode.refresh_from_db()
self.assertEqual(self.episode.issue_date, utc.localize(datetime.datetime(2014, 1, 6, 14, 0, 0)))
开发者ID:iago1460,项目名称:django-radio,代码行数:7,代码来源:test_schedules.py
示例12: test_pledge_creation_triggers_pact_success_when_goal_met
def test_pledge_creation_triggers_pact_success_when_goal_met(
self, create_notifications_for_users, send_notifications):
"""
Verify that when we create the last pledge needed to meet a Pact's goal,
the Pact is updated and an Event is created appropriately.
"""
# Setup scenario
now = utc_tz.localize(datetime(2015, 6, 1))
deadline = utc_tz.localize(datetime(2015, 6, 6))
pact = G(Pact, goal=2, deadline=deadline)
# Verify initial assumptions
self.assertEquals(0, Event.objects.count())
# Run code
with freeze_time(now):
G(Pledge, pact=pact)
# Run code and verify expectations
self.assertEqual(2, pact.pledge_count)
self.assertTrue(Event.objects.filter(name='pact_goal_met').exists())
self.assertEqual({
'subject': 'Pact Succeeded!',
'pact': pact.id,
'met_goal': True,
}, Event.objects.get(name='pact_goal_met').context)
self.assertEquals(
set([p.account for p in pact.pledge_set.all()]),
set(create_notifications_for_users.call_args_list[0][0][0]))
self.assertEquals(1, send_notifications.call_count)
开发者ID:jmcriffey,项目名称:crowdpact,代码行数:30,代码来源:tests.py
示例13: _gacha_availability
def _gacha_availability(self, cards, gacha_list):
print("trace _gacha_availability", cards)
gacha_map = {x.id: x for x in gacha_list}
ga = defaultdict(lambda: [])
for k in cards:
ga[k] # force the empty list to be created and cached
with self as s:
ents = s.query(GachaPresenceEntry).filter(GachaPresenceEntry.card_id.in_(cards)).all()
def getgacha(gid):
if gid in gacha_map:
return gacha_map[gid]
else:
return unknown_gacha_t("??? (unknown gacha ID: {0})".format(gid))
for e in ents:
if e.gacha_id_first == e.gacha_id_last or getgacha(e.gacha_id_first).name == getgacha(e.gacha_id_last).name:
name = getgacha(e.gacha_id_first).name
else:
name = None
# FIXME do this better
if name == "プラチナオーディションガシャ":
name = None
ga[e.card_id].append(Availability(Availability._TYPE_GACHA, name,
utc.localize(datetime.utcfromtimestamp(e.avail_start)), utc.localize(datetime.utcfromtimestamp(e.avail_end)), []))
[v.sort(key=lambda x: x.start) for v in ga.values()]
[combine_availability(v) for v in ga.values()]
return ga
开发者ID:islxyqwe,项目名称:sparklebox-schinese,代码行数:33,代码来源:models.py
示例14: test_dates_between_earlier_end_by_programme
def test_dates_between_earlier_end_by_programme(self):
self.programme.end_date = datetime.date(2014, 1, 7)
self.programme.save()
self.schedule.refresh_from_db()
self.assertCountEqual(
self.schedule.dates_between(
utc.localize(datetime.datetime(2014, 1, 1)), utc.localize(datetime.datetime(2014, 1, 14))),
[utc.localize(datetime.datetime(2014, 1, 6, 14, 0))])
开发者ID:iago1460,项目名称:django-radio,代码行数:8,代码来源:test_schedules.py
示例15: test_between_by_queryset
def test_between_by_queryset(self):
between = Transmission.between(
utc.localize(datetime.datetime(2015, 1, 6, 12, 0, 0)),
utc.localize(datetime.datetime(2015, 1, 6, 17, 0, 0)),
schedules=Schedule.objects.filter(
calendar=self.another_calendar).all())
self.assertListEqual(
[(t.slug, t.start) for t in list(between)],
[('classic-hits', utc.localize(datetime.datetime(2015, 1, 6, 16, 30, 0)))])
开发者ID:iago1460,项目名称:django-radio,代码行数:9,代码来源:test_schedules.py
示例16: test_between
def test_between(self):
between = Transmission.between(
utc.localize(datetime.datetime(2015, 1, 6, 11, 0, 0)),
utc.localize(datetime.datetime(2015, 1, 6, 17, 0, 0)))
self.assertListEqual(
[(t.slug, t.start) for t in list(between)],
[('the-best-wine', utc.localize(datetime.datetime(2015, 1, 6, 11, 0))),
('local-gossips', utc.localize(datetime.datetime(2015, 1, 6, 12, 0))),
('classic-hits', utc.localize(datetime.datetime(2015, 1, 6, 14, 0)))])
开发者ID:iago1460,项目名称:django-radio,代码行数:9,代码来源:test_schedules.py
示例17: _parse_value
def _parse_value(self, val_el, obj):
"""
Parse the node val_el as a constant.
"""
if val_el is not None and val_el.text is not None:
ntag = self._retag.match(val_el.tag).groups()[1]
else:
ntag = "Null"
obj.valuetype = ntag
if ntag == "Null":
obj.value = None
elif hasattr(ua.ua_binary.Primitives1, ntag):
# Elementary types have their parsing directly relying on ua_type_to_python.
obj.value = ua_type_to_python(val_el.text, ntag)
elif ntag == "DateTime":
obj.value = ua_type_to_python(val_el.text, ntag)
# According to specs, DateTime should be either UTC or with a timezone.
if obj.value.tzinfo is None or obj.value.tzinfo.utcoffset(obj.value) is None:
utc.localize(obj.value) # FIXME Forcing to UTC if unaware, maybe should raise?
elif ntag in ("ByteString", "String"):
mytext = val_el.text
if mytext is None:
# Support importing null strings.
mytext = ""
mytext = mytext.replace('\n', '').replace('\r', '')
obj.value = ua_type_to_python(mytext, ntag)
elif ntag == "Guid":
self._parse_contained_value(val_el, obj)
# Override parsed string type to guid.
obj.valuetype = ntag
elif ntag == "NodeId":
id_el = val_el.find("uax:Identifier", self.ns)
if id_el is not None:
obj.value = id_el.text
elif ntag == "ExtensionObject":
obj.value = self._parse_ext_obj(val_el)
elif ntag == "LocalizedText":
obj.value = self._parse_body(val_el)
elif ntag == "ListOfLocalizedText":
obj.value = self._parse_list_of_localized_text(val_el)
elif ntag == "ListOfExtensionObject":
obj.value = self._parse_list_of_extension_object(val_el)
elif ntag.startswith("ListOf"):
# Default case for "ListOf" types.
# Should stay after particular cases (e.g.: "ListOfLocalizedText").
obj.value = []
for val_el in val_el:
tmp = NodeData()
self._parse_value(val_el, tmp)
obj.value.append(tmp.value)
else:
# Missing according to string_to_val: XmlElement, ExpandedNodeId,
# QualifiedName, StatusCode.
# Missing according to ua.VariantType (also missing in string_to_val):
# DataValue, Variant, DiagnosticInfo.
self.logger.warning("Parsing value of type '%s' not implemented", ntag)
开发者ID:bitkeeper,项目名称:python-opcua,代码行数:57,代码来源:xmlparser.py
示例18: add_timestamps
def add_timestamps(self, item):
"""
Adds firstcreated and versioncreated timestamps to item
:param item: object which can be saved to ingest collection
:type item: dict
"""
item['firstcreated'] = utc.localize(item['firstcreated']) if item.get('firstcreated') else utcnow()
item['versioncreated'] = utc.localize(item['versioncreated']) if item.get('versioncreated') else utcnow()
开发者ID:MiczFlor,项目名称:superdesk-core,代码行数:10,代码来源:__init__.py
示例19: utc
def utc(cls,shift):
try:
s = utc.localize(shift.start)
e = utc.localize(shift.end)
except:
s = shift.start.astimezone(utc)
e = shift.end.astimezone(utc)
return shift_t(s,e)
开发者ID:avzahn,项目名称:remote_observing,代码行数:10,代码来源:shifts.py
示例20: backwards
def backwards(self, orm):
"Write your backwards methods here."
for meeting in orm.Meeting.objects.all():
t = meeting.begin_time.replace(tzinfo=None)
meeting.begin_time = utc.localize(t)
t = meeting.end_time.replace(tzinfo=None)
meeting.end_time = utc.localize(t)
meeting.save()
开发者ID:openplans,项目名称:meetingmatters,代码行数:10,代码来源:0002_Convert_all_the_times_entered_so_far_to_Eastern_Time.py
注:本文中的pytz.utc.localize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论