Here are the examples of the python api django.utils.timezone.utc taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
150 Examples
3
Example 1
Project: moma-django Source File: tests.py
def test_simple_time_reference_query_with_Q_gte_opr_negate(self):
qs = UniqueVisit.objects.filter(~Q(first_visit_date__gte =ISODate("2012-07-30T12:29:05Z")))
num = 0
self.assertEqual( qs.query.spec, dict({'first_visit_date': {'$lt': datetime(2012, 7, 30, 12, 29, 5, tzinfo=timezone.utc)}}))
for i in self.the_records:
if not(i['first_visit_date'] >= ISODate("2012-07-30T12:29:05Z")):
num += 1
self.assertEqual(qs.count(), num)
3
Example 2
def test_date_range(self):
result = self.parse_query('event.timestamp:>2016-01-01 event.timestamp:<2016-01-02')
assert result['date_from'] == datetime(2016, 1, 1, tzinfo=timezone.utc)
assert result['date_from_inclusive']
assert result['date_to'] == datetime(2016, 1, 2, tzinfo=timezone.utc)
assert not result['date_to_inclusive']
3
Example 3
def fetch_metrics(self, input_queue):
logger.info("%r fetching %s...", self.task, self.url)
self.start_time = time.time()
# Always use utc time with timezone info, see:
# https://docs.djangoproject.com/en/1.4/topics/i18n/timezones/#naive-and-aware-datetime-objects
self.task.last_attempt_time = datetime.datetime.utcfromtimestamp(
self.start_time).replace(tzinfo=timezone.utc)
client.getPage(str(self.url), timeout=self.collector_config.period - 1,
followRedirect=False).addCallbacks(
callback=self.success_callback, errback=self.error_callback,
callbackArgs=[input_queue], errbackArgs=[input_queue])
3
Example 4
Project: frikanalen Source File: views.py
def xmltv(request, year, month, day):
""" Program guide as XMLTV """
date = (datetime.datetime(year=int(year), month=int(month), day=int(day))
.replace(tzinfo=timezone.utc))
events = (Scheduleitem.objects
.by_day(date, days=1)
.order_by('starttime'))
return render(
request,
'agenda/xmltv.xml',
{
'channel_id': settings.CHANNEL_ID,
'channel_display_names': settings.CHANNEL_DISPLAY_NAMES,
'events': events,
'site_url': settings.SITE_URL,
},
content_type='application/xml')
3
Example 5
Project: django-twitter-tag Source File: test_tag.py
@httprettified
def test_datetime(self):
output, context = self.render(
template="""{% get_tweets for "jresig" as tweets %}""",
json_mocks='jeresig.json',
)
# Fri Mar 21 19:42:21 +0000 2008
if settings.USE_TZ:
# Get utc.
(context['tweets'][0]['datetime']).should.be.equal(datetime.datetime(2008, 3, 21, 19, 42, 21).replace(tzinfo=timezone.utc))
else:
(context['tweets'][0]['datetime']).should.be.equal(datetime.datetime(2008, 3, 21, 19, 42, 21))
3
Example 6
Project: wateronmars Source File: views.py
def request_for_cleanup(request):
"""Trigger a cleanup of all references that have never been saved
(past an arbitrary delay).
"""
delete_old_references(datetime.now(timezone.utc)-NEWS_TIME_THRESHOLD)
return HttpResponseRedirect(reverse("wom_user.views.home"))
3
Example 7
Project: moma-django Source File: tests.py
def test_delete_cascade_2nd_level(self):
pre1 = TestModel1.objects.all().count()
self.assertNotEqual(pre1, 0)
pre2 = TestModel2.objects.all().count()
self.assertNotEqual(pre2, 0)
pre3 = TestModel3.objects.all().count()
self.assertNotEqual(pre3, 0)
tm1o = TestModel1.objects.get(start_date = datetime(2005, 8, 28, tzinfo=timezone.utc), some_id =3)
tm1o.delete()
self.assertEqual(TestModel1.objects.all().count(), pre1-1)
self.assertEqual(TestModel2.objects.all().count(), pre2-1)
self.assertEqual(TestModel3.objects.all().count(), pre3-1)
3
Example 8
def test_valid_ipn_received(self):
ipn_obj = self.assertGotSignal(valid_ipn_received, False)
self.assertEqual(ipn_obj.last_name, u"User")
# Check date parsing
self.assertEqual(ipn_obj.payment_date,
datetime(2009, 2, 3, 7, 4, 6, tzinfo=timezone.utc))
3
Example 9
Project: hyperkitty Source File: test_incoming.py
def test_date_aware(self):
msg = Message()
msg["From"] = "[email protected]"
msg["Message-ID"] = "<dummy>"
msg["Date"] = "Fri, 02 Nov 2012 16:07:54 +0100"
msg.set_payload("Dummy message")
try:
add_to_list("example-list", msg)
except IntegrityError, e:
self.fail(e)
self.assertEqual(Email.objects.count(), 1)
stored_msg = Email.objects.all()[0]
expected = datetime.datetime(2012, 11, 2, 15, 7, 54,
tzinfo=timezone.utc)
self.assertEqual(stored_msg.date, expected)
self.assertEqual(stored_msg.timezone, 60)
3
Example 10
def test_working(self):
with open(p("test_mail_01.txt"), 'rb') as f:
process_mail.delay(f.read())
request = FoiRequest.objects.get_by_secret_mail("[email protected]")
messages = request.messages
self.assertEqual(len(messages), 2)
self.assertIn(u'J\xf6rg Gahl-Killen', [m.sender_name for m in messages])
message = messages[1]
self.assertEqual(message.timestamp,
datetime(2010, 7, 5, 5, 54, 40, tzinfo=timezone.utc))
3
Example 11
Project: django-blog-zinnia Source File: utils.py
def omniscient_datetime(*args):
"""
Generating a datetime aware or naive depending of USE_TZ.
"""
d = original_datetime(*args)
if settings.USE_TZ:
d = timezone.make_aware(d, timezone.utc)
return d
3
Example 12
Project: django-filer Source File: filemodels.py
@property
def canonical_time(self):
if settings.USE_TZ:
return int((self.uploaded_at - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds())
else:
return int((self.uploaded_at - datetime(1970, 1, 1)).total_seconds())
3
Example 13
def test_pagination(self):
make_content(TestContentObj,
published=datetime(2016, 5, 2, 14, 43, 0, tzinfo=timezone.utc),
_quantity=11)
resp = self.get_feed(page=1, page_size=5)
self.assertEqual(11, resp['count'])
self.assertEqual(5, len(resp['results']))
resp = self.get_feed(page=2, page_size=5)
self.assertEqual(5, len(resp['results']))
resp = self.get_feed(page=3, page_size=5)
self.assertEqual(1, len(resp['results']))
3
Example 14
Project: moma-django Source File: tests.py
def test_simple_time_reference_query_multiple_terms2(self):
qs = UniqueVisit.objects.filter(first_visit_date__lte =ISODate("2012-07-30T12:29:05Z"),time_on_site__gt =10)
num = 0
self.assertEqual( qs.query.spec, dict({'time_on_site': {'$gt': 10.0}, 'first_visit_date':
{'$lte': datetime(2012, 7, 30, 12, 29, 5, tzinfo=timezone.utc)}}))
for i in self.the_records:
if i['first_visit_date'] <= ISODate("2012-07-30T12:29:05Z") and i['time_on_site'] > 10:
num += 1
self.assertEqual(qs.count(), num)
3
Example 15
def setUp(self):
self.這馬時間patcher = patch('django.utils.timezone.now')
這馬時間mock = self.這馬時間patcher.start()
這馬時間mock.return_value = datetime(2012, 12, 28, tzinfo=timezone.utc)
管理 = 使用者表管理()
self.使用者 = 管理.create_superuser('[email protected]', 'I\'m sui2')
3
Example 16
Project: moma-django Source File: tests.py
def test_delete_referenced_object_m1_m2_with_cascade(self):
pre1 = TestModel1.objects.all().count()
self.assertNotEqual(pre1, 0)
pre2 = TestModel2.objects.all().count()
self.assertNotEqual(pre2, 0)
pre3 = TestModel3.objects.all().count()
self.assertNotEqual(pre3, 0)
tm1o = TestModel1.objects.get(start_date = datetime(2005, 7, 28, tzinfo=timezone.utc), some_id =2)
tm1o.delete()
self.assertEqual(TestModel1.objects.all().count(), pre1-1)
self.assertEqual(TestModel2.objects.all().count(), pre2-1)
self.assertEqual(pre3, TestModel3.objects.all().count())
3
Example 17
@with_gpg_obj
def key_state(key, gpg):
results = gpg.import_keys(key).results
keys = gpg.list_keys()
if not results or not results[0]["fingerprint"]:
return None, "invalid"
else:
state = "valid"
result = results[0]
for key in keys:
if key["fingerprint"] == result["fingerprint"]:
exp_timestamp = int(key["expires"]) if key["expires"] else 0
expires = datetime.fromtimestamp(exp_timestamp, timezone.utc)
if key["trust"] == "r":
state = "revoked"
elif exp_timestamp and expires < timezone.now():
state = "expired"
break
return result["fingerprint"], state
3
Example 18
def test_timestamp(self):
timestamp = timezone.now().replace(microsecond=0, tzinfo=timezone.utc) - datetime.timedelta(hours=1)
kwargs = {u'message': 'hello', 'timestamp': timestamp.strftime('%s.%f')}
resp = self._postWithSignature(kwargs)
assert resp.status_code == 200, resp.content
instance = Event.objects.get()
assert instance.message == 'hello'
assert instance.datetime == timestamp
group = instance.group
assert group.first_seen == timestamp
assert group.last_seen == timestamp
3
Example 19
Project: PyClassLessons Source File: file.py
def _last_modification(self):
"""
Return the modification time of the file storing the session's content.
"""
modification = os.stat(self._key_to_file()).st_mtime
if settings.USE_TZ:
modification = datetime.datetime.utcfromtimestamp(modification)
modification = modification.replace(tzinfo=timezone.utc)
else:
modification = datetime.datetime.fromtimestamp(modification)
return modification
3
Example 20
Project: hyperkitty Source File: test_incoming.py
def test_date_naive(self):
msg = Message()
msg["From"] = "[email protected]"
msg["Message-ID"] = "<dummy>"
msg["Date"] = "Fri, 02 Nov 2012 16:07:54"
msg.set_payload("Dummy message")
try:
add_to_list("example-list", msg)
except IntegrityError as e:
self.fail(e)
self.assertEqual(Email.objects.count(), 1)
stored_msg = Email.objects.all()[0]
expected = datetime.datetime(2012, 11, 2, 16, 7, 54,
tzinfo=timezone.utc)
self.assertEqual(stored_msg.date, expected)
self.assertEqual(stored_msg.timezone, 0)
3
Example 21
Project: django-calendarium Source File: utils.py
def monday_of_week(year, week):
"""
Returns a datetime for the monday of the given week of the given year.
"""
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
day=str_time.tm_mday, tzinfo=timezone.utc)
if timezone.datetime(year, 1, 4).isoweekday() > 4:
# ISO 8601 where week 1 is the first week that has at least 4 days in
# the current year
date -= timezone.timedelta(days=7)
return date
3
Example 22
Project: newspeak Source File: utils.py
def datetime_from_struct(time):
"""
Convert a time_struct to a datetime object.
Source: http://stackoverflow.com/questions/1697815/how-do-you-convert-a-python-time-struct-time-object-into-a-datetime-object
"""
dt = datetime.fromtimestamp(mktime(time))
# Assume this is in the local time zone
dt = dt.replace(tzinfo=timezone.utc)
return dt
3
Example 23
def year_lookup_bounds_for_datetime_field(self, value):
# cx_Oracle doesn't support tz-aware datetimes
bounds = super(DatabaseOperations, self).year_lookup_bounds_for_datetime_field(value)
if settings.USE_TZ:
bounds = [b.astimezone(timezone.utc) for b in bounds]
return [Oracle_datetime.from_datetime(b) for b in bounds]
3
Example 24
Project: django-twitter-tag Source File: twitter_tag.py
def enrich(self, tweet):
""" Apply the local presentation logic to the fetched data."""
tweet = urlize_tweet(expand_tweet_urls(tweet))
# parses created_at "Wed Aug 27 13:08:45 +0000 2008"
if settings.USE_TZ:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y').replace(tzinfo=timezone.utc)
else:
tweet['datetime'] = datetime.strptime(tweet['created_at'], '%a %b %d %H:%M:%S +0000 %Y')
return tweet
3
Example 25
Project: froide Source File: test_mail.py
@override_settings(FOI_EMAIL_DOMAIN=['fragdenstaat.de', 'example.com'])
def test_additional_domains(self):
with open(p("test_mail_01.txt"), 'rb') as f:
process_mail.delay(f.read().replace(b'@fragdenstaat.de', b'@example.com'))
request = FoiRequest.objects.get_by_secret_mail("[email protected]")
messages = request.messages
self.assertEqual(len(messages), 2)
self.assertIn(u'J\xf6rg Gahl-Killen', [m.sender_name for m in messages])
message = messages[1]
self.assertEqual(message.timestamp,
datetime(2010, 7, 5, 5, 54, 40, tzinfo=timezone.utc))
3
Example 26
Project: djangogirls Source File: csv.py
@property
def start(self):
if not self.start_raw:
return None
return (datetime.strptime(self.start_raw, '%Y-%m-%d %H:%M:%S')
.replace(tzinfo=timezone.utc))
3
Example 27
Project: django Source File: storage.py
def _datetime_from_timestamp(self, ts):
"""
If timezone support is enabled, make an aware datetime object in UTC;
otherwise make a naive one in the local timezone.
"""
if settings.USE_TZ:
# Safe to use .replace() because UTC doesn't have DST
return datetime.utcfromtimestamp(ts).replace(tzinfo=timezone.utc)
else:
return datetime.fromtimestamp(ts)
3
Example 28
Project: betty-cropper Source File: test_image_model.py
@pytest.mark.django_db
def test_last_modified_auto_now():
with freeze_time('2016-05-02 01:02:03'):
image = Image.objects.create(
name="Lenna.gif",
width=512,
height=512
)
assert image.last_modified == timezone.datetime(2016, 5, 2, 1, 2, 3, tzinfo=timezone.utc)
with freeze_time('2016-12-02 01:02:03'):
image.save()
assert image.last_modified == timezone.datetime(2016, 12, 2, 1, 2, 3, tzinfo=timezone.utc)
3
Example 29
Project: django-basis Source File: tests.py
@override_settings(USE_TZ=True)
def test_datetimes_with_timezone(self):
person = TimeStampPerson.objects.create()
self.assertEqual(person.created_at.tzinfo, timezone.utc)
self.assertEqual(person.updated_at.tzinfo, timezone.utc)
self.assertAlmostEqual(int(person.created_at.strftime('%Y%m%d%H%M%S')),
int(timezone.now().strftime('%Y%m%d%H%M%S')))
person.save()
self.assertNotEqual(person.created_at, person.updated_at)
self.assertAlmostEqual(int(person.updated_at.strftime('%Y%m%d%H%M%S')),
int(timezone.now().strftime('%Y%m%d%H%M%S')))
3
Example 30
Project: django-vkontakte-wall Source File: tests.py
@mock.patch('vkontakte_users.models.User.remote.fetch', side_effect=user_fetch_mock)
def test_fetch_group_post_updating_initial_reposts_time_from(self, *args, **kwargs):
group = GroupFactory(remote_id=GROUP_ID)
post = PostFactory(remote_id=GROUP_POST_ID, owner=group)
post.reposts_users.through.objects.bulk_create([post.reposts_users.through(user_id=1, post_id=post.pk)])
self.assertEqual(post.reposts_users.through.objects.count(), 1)
resources = [{'from_id': 1, 'date': int(time.time())}]
with mock.patch('vkontakte_wall.models.Post.fetch_reposts_items', side_effect=lambda **kw: resources):
post.fetch_reposts(all=True)
self.assertEqual(post.reposts_users.through.objects.count(), 1)
instance = post.reposts_users.through.objects.all()[0]
self.assertEqual(instance.user_id, 1)
self.assertEqual(instance.post_id, post.pk)
self.assertEqual(instance.time_from, datetime.fromtimestamp(resources[0]['date'], tz=timezone.utc))
3
Example 31
Project: moma-django Source File: tests.py
def test_simple_time_reference_query(self):
qs = UniqueVisit.objects.filter(first_visit_date__lte =ISODate("2012-07-30T12:29:05Z"))
num = 0
self.assertEqual( qs.query.spec, dict({'first_visit_date': {'$lte': datetime(2012, 7, 30, 12, 29, 5, tzinfo=timezone.utc)}}))
for i in self.the_records:
if i['first_visit_date'] <= ISODate("2012-07-30T12:29:05Z"):
num += 1
self.assertEqual(qs.count(), num)
3
Example 32
Project: wateronmars Source File: views.py
def request_for_update(request):
"""Trigger the collection of news from all known feeds and the cleanup
of all references that have never been saved (past an arbitrary
delay).
"""
delete_old_references(datetime.now(timezone.utc)-NEWS_TIME_THRESHOLD)
collect_news_from_feeds()
if settings.DEMO:
# keep only a short number of refs (the most recent) to avoid bloating the demo
with transaction.commit_on_success():
for ref in list(Reference.objects\
.filter(save_count=0)\
.order_by("-pub_date")[MAX_ITEMS_PER_PAGE:]):
ref.delete()
return HttpResponseRedirect(reverse("wom_user.views.home"))
3
Example 33
Project: moma-django Source File: tests.py
def test_simple_time_reference_query_multiple_terms3(self):
qs = UniqueVisit.objects.filter(first_visit_date__lte =ISODate("2012-07-30T12:29:05Z"),time_on_site__gt =10,
page_views__gt =2)
num = 0
self.assertEqual( qs.query.spec, dict({'time_on_site': {'$gt': 10.0}, 'page_views': {'$gt': 2},
'first_visit_date': {'$lte': datetime(2012, 7, 30, 12, 29, 5, tzinfo=timezone.utc)}}))
for i in self.the_records:
if i['first_visit_date'] <= ISODate("2012-07-30T12:29:05Z") and \
i['time_on_site'] > 10 and \
i['page_views'] > 2:
num += 1
self.assertEqual(qs.count(), num)
3
Example 34
@register.filter
def utc(value):
"""
Converts a datetime to UTC.
"""
return do_timezone(value, timezone.utc)
3
Example 35
Project: moma-django Source File: tests.py
def test_simple_time_reference_query_with_Q_3_AND_negated(self):
qs = UniqueVisit.objects.filter(~(Q(time_on_site =10)&(~Q(first_visit_date =ISODate("2012-07-30T12:29:05Z")))&
Q(visit_count__lte =2)))
num = 0
self.assertEqual( qs.query.spec, dict(
{'$or': [{'time_on_site': {'$ne': 10.0}}, {'visit_count': {'$gt': 2}},
{'first_visit_date': datetime(2012, 7, 30, 12, 29, 5, tzinfo=timezone.utc)}]}
))
for i in self.the_records:
if not(i['time_on_site'] == 10 and
not i['first_visit_date'] == ISODate("2012-07-30T12:29:05Z") and
i['visit_count']<=2):
num += 1
qs = qs.filter(account__in=self.list_of_accounts)
self.assertEqual(qs.count(), num)
3
Example 36
@register.filter
def to_localtime(time):
'''
A function to convert naive datetime to
localtime base on settings
'''
utc_time = time.replace(tzinfo=timezone.utc)
to_zone = timezone.get_default_timezone()
return utc_time.astimezone(to_zone)
3
Example 37
Project: moma-django Source File: tests.py
def test_delete_of_queryset(self):
pre1 = TestModel1.objects.all().count()
self.assertNotEqual(pre1, 0)
pre2 = TestModel2.objects.all().count()
self.assertNotEqual(pre2, 0)
pre3 = TestModel3.objects.all().count()
self.assertNotEqual(pre3, 0)
TestModel1.objects.filter(start_date = datetime(2005, 7, 28, tzinfo=timezone.utc), some_id =2).delete()
self.assertEqual(TestModel1.objects.all().count(), pre1-1)
# Delete through the filter will behave differently and will not follow a cascade relationship
# (see different behaviour in test_delete_referenced_object_m1_m2)
self.assertEqual(TestModel2.objects.all().count(), pre2)
self.assertEqual(pre3, TestModel3.objects.all().count())
3
Example 38
def test_valid_ipn_received(self):
ipn_obj = self.assertGotSignal(valid_ipn_received, False)
# Check some encoding issues:
self.assertEqual(ipn_obj.first_name, u"J\u00f6rg")
# Check date parsing
self.assertEqual(ipn_obj.payment_date,
datetime(2009, 2, 3, 7, 4, 6, tzinfo=timezone.utc))
3
Example 39
def create_sample_event(self, platform):
event = create_sample_event(
project=self.project,
platform=platform,
event_id='d964fdbd649a4cf8bfc35d18082b6b0e',
timestamp=1452683305,
)
event.group.update(
first_seen=datetime(2015, 8, 13, 3, 8, 25, tzinfo=timezone.utc),
last_seen=datetime(2016, 1, 13, 3, 8, 25, tzinfo=timezone.utc),
)
return event
3
Example 40
Project: nodewatcher Source File: frontend.py
def extra_context(context):
# Get the node's local timezone using the location schema.
try:
# TODO: Should this go to some method on the node class?
node_zone = context['node'].config.core.location().timezone or timezone.utc
except (registry_exceptions.RegistryItemNotRegistered, AttributeError):
node_zone = timezone.utc
try:
timezone_offset = node_zone.utcoffset(datetime.datetime.now(), is_dst=False)
except TypeError:
# Timezone does not have a is_dst keyword argument.
timezone_offset = node_zone.dst(datetime.datetime.now())
return {
# Python and JavaScript timezone offsets are inverted.
'timezone_offset': -int(timezone_offset.total_seconds() // 60)
}
3
Example 41
Project: sentry Source File: tests.py
def test_timestamp_as_iso(self):
timestamp = timezone.now().replace(microsecond=0, tzinfo=timezone.utc) - datetime.timedelta(hours=1)
kwargs = {u'message': 'hello', 'timestamp': timestamp.strftime('%Y-%m-%dT%H:%M:%S.%f')}
resp = self._postWithSignature(kwargs)
assert resp.status_code == 200, resp.content
instance = Event.objects.get()
assert instance.message == 'hello'
assert instance.datetime == timestamp
group = instance.group
assert group.first_seen == timestamp
assert group.last_seen == timestamp
3
Example 42
Project: pinax-stripe Source File: test_utils.py
def test_conversion_with_field_name(self):
stamp = convert_tstamp({"my_date": 1365567407}, "my_date")
self.assertEquals(
stamp,
datetime.datetime(2013, 4, 10, 4, 16, 47, tzinfo=timezone.utc)
)
3
Example 43
def parsedate(datestring):
if datestring is None:
return None
try:
parsed = dateutil.parser.parse(datestring)
except ValueError:
return None
if parsed.utcoffset() is not None and \
abs(parsed.utcoffset()) > timedelta(hours=13):
parsed = parsed.astimezone(timezone.utc)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc) # make it aware
return parsed
3
Example 44
Project: minos Source File: quota_util.py
@transaction.commit_on_success
def update_cluster(self, cluster):
logger.info("start update cluster %s" % cluster.name),
cluster_name = cluster.name
now = time.time()
quota_list = utils.hadoop_util.get_quota_summary(cluster_name)
quota_injector.push_quota_to_tsdb(quota_list, cluster_name)
for quota in quota_list:
quota_record, ok = Quota.objects.get_or_create(cluster=cluster, name=quota['name'])
quota_record.quota = quota['quota']
quota_record.used_quota = quota['used_quota']
quota_record.remaining_quota = quota['remaining_quota']
quota_record.space_quota = quota['space_quota']
quota_record.used_space_quota = quota['used_space_quota']
quota_record.remaining_space_quota = quota['remaining_space_quota']
quota_record.last_update_time = datetime.datetime.utcfromtimestamp(
now).replace(tzinfo=timezone.utc)
quota_record.save()
logger.info("end update cluster %s" % cluster.name),
3
Example 45
def setUp(self):
site = factories.make_world()
date = datetime(2010, 6, 5, 5, 54, 40, tzinfo=timezone.utc)
req = factories.FoiRequestFactory.create(site=site,
secret_address="[email protected]",
first_message=date, last_message=date)
factories.FoiMessageFactory.create(request=req, timestamp=date)
3
Example 46
Project: pinax-stripe Source File: test_utils.py
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(
stamp,
datetime.datetime(2013, 4, 10, 4, 16, 47, tzinfo=timezone.utc)
)
3
Example 47
def convert_tstamp(response, field_name=None):
tz = timezone.utc if settings.USE_TZ else None
if field_name and response.get(field_name):
return datetime.datetime.fromtimestamp(
response[field_name],
tz
)
if response is not None and not field_name:
return datetime.datetime.fromtimestamp(
response,
tz
)
3
Example 48
Project: django-vkontakte-wall Source File: tests.py
def test_fetch_group_wall_before(self):
# TODO: finish test
group = GroupFactory(remote_id=34384434, screen_name='topmelody')
before = datetime(2013, 10, 3, tzinfo=timezone.utc)
after = datetime(2013, 10, 1, tzinfo=timezone.utc)
posts = group.fetch_posts(all=True, before=before, after=after, filter='owner')
3
Example 49
Project: betty-cropper Source File: test_crop_utils.py
def test_check_not_modified_has_if_modified_since_header():
request = HttpRequest()
request.META['HTTP_IF_MODIFIED_SINCE'] = "Sun, 06 Nov 1994 08:49:37 GMT"
# Fails if "last_modified" invalid
assert not check_not_modified(request, None)
# Before
when = datetime(1994, 11, 6, 8, 49, 37, tzinfo=timezone.utc)
assert check_not_modified(request, when - timedelta(seconds=1))
# Identical
assert check_not_modified(request, when)
# After
assert not check_not_modified(request, when + timedelta(seconds=1))
3
Example 50
@cached_property
def timezone(self):
"""
Time zone for datetimes stored as naive values in the database.
Returns a tzinfo object or None.
This is only needed when time zone support is enabled and the database
doesn't support time zones. (When the database supports time zones,
the adapter handles aware datetimes so Django doesn't need to.)
"""
if not settings.USE_TZ:
return None
elif self.features.supports_timezones:
return None
elif self.settings_dict['TIME_ZONE'] is None:
return timezone.utc
else:
return pytz.timezone(self.settings_dict['TIME_ZONE'])