def generate_weeks(count=500, until_date=None): this_dow = date.today().weekday() monday = date.today() - timedelta(days=this_dow) end = monday for i in xrange(count): start = end - timedelta(days=7) ret = (start, end) end = start if start > until_date: yield ret else: return
def parsedate_to_datetime(data): _3to2list = list(_parsedate_tz(data)) dtuple, tz, = [_3to2list[:-1]] + _3to2list[-1:] if tz is None: return datetime.datetime(*dtuple[:6]) return datetime.datetime(*dtuple[:6], tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
def localtime(dt=None, isdst=-1): """Return local time as an aware datetime object. If called without arguments, return current time. Otherwise *dt* argument should be a datetime instance, and it is converted to the local time zone according to the system time zone database. If *dt* is naive (that is, dt.tzinfo is None), it is assumed to be in local time. In this case, a positive or zero value for *isdst* causes localtime to presume initially that summer time (for example, Daylight Saving Time) is or is not (respectively) in effect for the specified time. A negative value for *isdst* causes the localtime() function to attempt to divine whether summer time is in effect for the specified time. """ if dt is None: return datetime.datetime.now(datetime.timezone.utc).astimezone() if dt.tzinfo is not None: return dt.astimezone() # We have a naive datetime. Convert to a (localtime) timetuple and pass to # system mktime together with the isdst hint. System mktime will return # seconds since epoch. tm = dt.timetuple()[:-1] + (isdst,) seconds = time.mktime(tm) localtm = time.localtime(seconds) try: delta = datetime.timedelta(seconds=localtm.tm_gmtoff) tz = datetime.timezone(delta, localtm.tm_zone) except AttributeError: # Compute UTC offset and compare with the value implied by tm_isdst. # If the values match, use the zone name implied by tm_isdst. delta = dt - datetime.datetime(*time.gmtime(seconds)[:6]) dst = time.daylight and localtm.tm_isdst > 0 gmtoff = -(time.altzone if dst else time.timezone) if delta == datetime.timedelta(seconds=gmtoff): tz = datetime.timezone(delta, time.tzname[dst]) else: tz = datetime.timezone(delta) return dt.replace(tzinfo=tz)
class UserReport(models.Model): today_date = datetime.today().day user_today_cnt = UserProfile.objects.filter( register_date=datetime.today()).count() user_yesterday_cnt = UserProfile.objects.filter( register_date=(datetime.today() - timedelta(days=1))).count() user_increase = user_today_cnt - user_yesterday_cnt class Meta: verbose_name = u'用户统计报告' verbose_name_plural = verbose_name def __str__(self): return str(self.today_date)
def test_queue_metrics(self): queue_id = self._temp_queue("TestTempQueue") task1 = self._create_temp_queued_task("temp task 1", queue_id) time.sleep(1) task2 = self._create_temp_queued_task("temp task 2", queue_id) self.api.queues.get_next_task(queue=queue_id) self.api.queues.remove_task(queue=queue_id, task=task2["id"]) to_date = utc_now_tz_aware() from_date = to_date - timedelta(hours=1) res = self.api.queues.get_queue_metrics( queue_ids=[queue_id], from_date=from_date.timestamp(), to_date=to_date.timestamp(), interval=5, ) self.assertMetricQueues(res["queues"], queue_id)
def assertMetricQueues(self, queues_data, queue_id): self.assertEqual(len(queues_data), 1) queue_res = queues_data[0] self.assertEqual(queue_res.queue, queue_id) dates_len = len(queue_res["dates"]) self.assertTrue(2 >= dates_len >= 1) for prop in ("avg_waiting_times", "queue_lengths"): self.assertEqual(len(queue_res[prop]), dates_len) dates_in_sec = [d / 1000 for d in queue_res["dates"]] self.assertGreater( dates_in_sec[0], (utc_now_tz_aware() - timedelta(seconds=15)).timestamp() ) if dates_len > 1: self.assertAlmostEqual(dates_in_sec[1] - dates_in_sec[0], 5, places=0)
def get_partitions(): get_partitions = 'SELECT [PARTITION_INDEX] FROM [wbsn-data-security].[dbo].[PA_EVENT_PARTITION_CATALOG] where ' \ 'STATUS = \'ONLINE_ACTIVE\' or STATUS = \'ONLINE\'' partitions = execute_sql(get_partitions).fetchall() normalised_partitions = [] for partition in partitions: normalised_partitions.append(partition[0]) iterator = 0 for partitions in normalised_partitions: date_string = f'{str(partitions)[0:4]}-{str(partitions)[4:6]}-{str(partitions)[6:]}' date_time_obj = datetime.strptime(date_string, '%Y-%m-%d') now_minus_90 = datetime.now() - timedelta(days=120) if date_time_obj < now_minus_90: normalised_partitions.pop(iterator) iterator += 1 return normalised_partitions
def get_late_serial_holdings_pids(cls): """Return pids for all late holdings. The holdings is considered late if : * it is of type serial * it is considerate as alive (acq_status='currently_received') * next expected date has passed (greater than current datetime). :return a generator of holdings pid. """ from ...holdings.api import HoldingsSearch yesterday = datetime.now(timezone.utc) - timedelta(days=1) yesterday = yesterday.strftime('%Y-%m-%d') results = HoldingsSearch() \ .filter('term', holdings_type='serial') \ .filter('term', acquisition_status='currently_received') \ .filter('range', patterns__next_expected_date={'lte': yesterday}) \ .params(preserve_order=True) \ .sort({'_created': {'order': 'asc'}}) \ .source(['pid']).scan() for hit in results: yield hit.pid
USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=1), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'AUTH_HEADER_TYPES': ('JWT', 'Bearer'), } ACCOUNT_LOGOUT_ON_GET = True
def ReturnDateNextBackup(DataAnt, timebackup): # recebe temp e timeBackup e retorna date_time_obj = datetime.datetime.strptime(str(DataAnt), '%Y-%m-%d ') temp = date_time_obj.date() d = temp + timedelta(days=(int(timebackup))) return d
def create(self, phone_number, otp): phone_otp = self.model(phone_number=phone_number, otp=otp) expiry = timezone.now() + timedelta(minutes=2) phone_otp.expiry = expiry phone_otp.save() return phone_otp
}, ] # Internationalization # https://docs.djangoproject.com/en/2.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.1/howto/static-files/ STATIC_URL = '/static/' AUTH_USER_MODEL = 'accounts.User' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication', ) } REST_KNOX = { 'USER_SERIALIZER': 'accounts.serializers.UserSerializer', 'TOKEN_TTL': timedelta(hours=24 + 7), }