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