Python dateutil.tz.tzutc() Examples
The following are 30
code examples of dateutil.tz.tzutc().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
dateutil.tz
, or try the search function
.
Example #1
Source File: test_comparisons.py From vnpy_crypto with MIT License | 6 votes |
def test_cant_compare_tz_naive_w_aware_dateutil(self): # see gh-1404 a = Timestamp('3/12/2012') b = Timestamp('3/12/2012', tz=tzutc()) pytest.raises(Exception, a.__eq__, b) pytest.raises(Exception, a.__ne__, b) pytest.raises(Exception, a.__lt__, b) pytest.raises(Exception, a.__gt__, b) pytest.raises(Exception, b.__eq__, a) pytest.raises(Exception, b.__ne__, a) pytest.raises(Exception, b.__lt__, a) pytest.raises(Exception, b.__gt__, a) if PY2: pytest.raises(Exception, a.__eq__, b.to_pydatetime()) pytest.raises(Exception, a.to_pydatetime().__eq__, b) else: assert not a == b.to_pydatetime() assert not a.to_pydatetime() == b
Example #2
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testInZoneFoldEquality(self): # Two datetimes in the same zone are considered to be equal if their # wall times are equal, even if they have different absolute times. tzname = self._get_tzname('America/New_York') with self._gettz_context(tzname): NYC = self.gettz(tzname) UTC = tz.tzutc() dt0 = datetime(2011, 11, 6, 1, 30, tzinfo=NYC) dt1 = tz.enfold(dt0, fold=1) # Make sure these actually represent different times self.assertNotEqual(dt0.astimezone(UTC), dt1.astimezone(UTC)) # Test that they compare equal self.assertEqual(dt0, dt1)
Example #3
Source File: test_poll_request.py From django-taxii-services with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_02(self): """ Test a begin TS later than an end TS. """ begin_ts = datetime.now(tzutc()) end_ts = begin_ts - timedelta(days=7) pp = tm11.PollParameters() pr = tm11.PollRequest(message_id=generate_message_id(), collection_name='default', poll_parameters=pp, exclusive_begin_timestamp_label=begin_ts, inclusive_end_timestamp_label=end_ts) make_request('/test_poll_1/', pr.to_xml(), get_headers(VID_TAXII_SERVICES_11, False), MSG_STATUS_MESSAGE)
Example #4
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testFoldLondon(self): tzname = self._get_tzname('Europe/London') with self._gettz_context(tzname): LON = self.gettz(tzname) UTC = tz.tzutc() t0_u = datetime(2013, 10, 27, 0, 30, tzinfo=UTC) # BST t1_u = datetime(2013, 10, 27, 1, 30, tzinfo=UTC) # GMT t0 = t0_u.astimezone(LON) t1 = t1_u.astimezone(LON) self.assertEqual(t0.replace(tzinfo=None), datetime(2013, 10, 27, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2013, 10, 27, 1, 30)) self.assertEqual(t0.utcoffset(), timedelta(hours=1)) self.assertEqual(t1.utcoffset(), timedelta(hours=0))
Example #5
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testGapNegativeUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('America/Toronto') with self._gettz_context(tzname): TOR = self.gettz(tzname) t0_u = datetime(2011, 3, 13, 6, 30, tzinfo=tz.tzutc()) t1_u = datetime(2011, 3, 13, 7, 30, tzinfo=tz.tzutc()) t0 = t0_u.astimezone(TOR) t1 = t1_u.astimezone(TOR) self.assertEqual(t0.replace(tzinfo=None), datetime(2011, 3, 13, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2011, 3, 13, 3, 30)) self.assertNotEqual(t0, t1) self.assertEqual(t0.utcoffset(), timedelta(hours=-5.0)) self.assertEqual(t1.utcoffset(), timedelta(hours=-4.0))
Example #6
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testGapPositiveUTCOffset(self): # Test that we don't have a problem around gaps. tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD = self.gettz(tzname) t0_u = datetime(2012, 10, 6, 15, 30, tzinfo=tz.tzutc()) # AEST t1_u = datetime(2012, 10, 6, 16, 30, tzinfo=tz.tzutc()) # AEDT t0 = t0_u.astimezone(SYD) t1 = t1_u.astimezone(SYD) self.assertEqual(t0.replace(tzinfo=None), datetime(2012, 10, 7, 1, 30)) self.assertEqual(t1.replace(tzinfo=None), datetime(2012, 10, 7, 3, 30)) self.assertEqual(t0.utcoffset(), timedelta(hours=10)) self.assertEqual(t1.utcoffset(), timedelta(hours=11))
Example #7
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testFoldPositiveUTCOffset(self): # Test that we can resolve ambiguous times tzname = self._get_tzname('Australia/Sydney') with self._gettz_context(tzname): SYD = self.gettz(tzname) t0_u = datetime(2012, 3, 31, 15, 30, tzinfo=tz.tzutc()) # AEST t1_u = datetime(2012, 3, 31, 16, 30, tzinfo=tz.tzutc()) # AEDT t0_syd0 = t0_u.astimezone(SYD) t1_syd1 = t1_u.astimezone(SYD) self.assertEqual(t0_syd0.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t1_syd1.replace(tzinfo=None), datetime(2012, 4, 1, 2, 30)) self.assertEqual(t0_syd0.utcoffset(), timedelta(hours=11)) self.assertEqual(t1_syd1.utcoffset(), timedelta(hours=10))
Example #8
Source File: auth.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def check_date(request) -> bool: raw_date = request.headers.get('Date') if not raw_date: raw_date = request.headers.get('X-BackendAI-Date', request.headers.get('X-Sorna-Date')) if not raw_date: return False try: # HTTP standard says "Date" header must be in GMT only. # However, dateutil.parser can recognize other commonly used # timezone names and offsets. date = dtparse(raw_date, tzinfos=whois_timezone_info) if date.tzinfo is None: date = date.replace(tzinfo=tzutc()) # assume as UTC now = datetime.now(tzutc()) min_date = now - timedelta(minutes=15) max_date = now + timedelta(minutes=15) request['date'] = date request['raw_date'] = raw_date if not (min_date < date < max_date): return False except ValueError: return False return True
Example #9
Source File: isoparser.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants
Example #10
Source File: utils.py From faces with GNU General Public License v2.0 | 6 votes |
def datetime2timestamp(dt, default_timezone=None): """Calculate the timestamp based on the given datetime instance. :type dt: datetime :param dt: A datetime object to be converted into timestamp :type default_timezone: tzinfo :param default_timezone: If it is provided as None, we treat it as tzutc(). But it is only used when dt is a naive datetime. :returns: The timestamp """ epoch = datetime.datetime(1970, 1, 1) if dt.tzinfo is None: if default_timezone is None: default_timezone = tzutc() dt = dt.replace(tzinfo=default_timezone) d = dt.replace(tzinfo=None) - dt.utcoffset() - epoch if hasattr(d, "total_seconds"): return d.total_seconds() # Works in Python 2.7+ return (d.microseconds + (d.seconds + d.days * 24 * 3600) * 10**6) / 10**6
Example #11
Source File: registry.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def set_kernel_status(self, kernel_id: KernelId, status: KernelStatus, reason: str = '', *, db_conn: SAConnection = None): assert status != KernelStatus.TERMINATED, \ 'TERMINATED status update must be handled in ' \ 'mark_kernel_terminated()' data = { 'status': status, 'status_info': reason, 'status_changed': datetime.now(tzutc()), } async with reenter_txn(self.dbpool, db_conn) as conn: query = ( sa.update(kernels) .values(data) .where(kernels.c.id == kernel_id) ) await conn.execute(query)
Example #12
Source File: deleted_asset_test.py From contentful.py with MIT License | 6 votes |
def test_deleted_asset(self): deleted_asset = DeletedAsset({ "sys": { "space": { "sys": { "type": "Link", "linkType": "Space", "id": "cfexampleapi" } }, "id": "5c6VY0gWg0gwaIeYkUUiqG", "type": "DeletedAsset", "createdAt": "2013-09-09T16:17:12.600Z", "updatedAt": "2013-09-09T16:17:12.600Z", "deletedAt": "2013-09-09T16:17:12.600Z", "revision": 1 } }) self.assertEqual(deleted_asset.id, '5c6VY0gWg0gwaIeYkUUiqG') self.assertEqual(deleted_asset.deleted_at, datetime.datetime(2013, 9, 9, 16, 17, 12, 600000, tzinfo=tzutc())) self.assertEqual(str(deleted_asset), "<DeletedAsset id='5c6VY0gWg0gwaIeYkUUiqG'>")
Example #13
Source File: deleted_entry_test.py From contentful.py with MIT License | 6 votes |
def test_deleted_entry(self): deleted_entry = DeletedEntry({ "sys": { "space": { "sys": { "type": "Link", "linkType": "Space", "id": "cfexampleapi" } }, "id": "5c6VY0gWg0gwaIeYkUUiqG", "type": "DeletedEntry", "createdAt": "2013-09-09T16:17:12.600Z", "updatedAt": "2013-09-09T16:17:12.600Z", "deletedAt": "2013-09-09T16:17:12.600Z", "revision": 1 } }) self.assertEqual(deleted_entry.id, '5c6VY0gWg0gwaIeYkUUiqG') self.assertEqual(deleted_entry.deleted_at, datetime.datetime(2013, 9, 9, 16, 17, 12, 600000, tzinfo=tzutc())) self.assertEqual(str(deleted_entry), "<DeletedEntry id='5c6VY0gWg0gwaIeYkUUiqG'>")
Example #14
Source File: test_conversation.py From python-rest-api with BSD 2-Clause "Simplified" License | 6 votes |
def test_conversation_start(self): http_client = Mock() http_client.request.return_value = '{"id":"1234","contactId":"1234","contact":{"id":"1234","href":"https://contacts.messagebird.com/v2/contacts/1234","msisdn":99999999999,"displayName":"99999999999","firstName":"","lastName":"","customDetails":{},"attributes":{},"createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:19:38Z"},"channels":[{"id":"1234","name":"channel-name","platformId":"sms","status":"active","createdDatetime":"2019-04-01T15:25:12Z","updatedDatetime":"0001-01-01T00:00:00Z"}],"status":"active","createdDatetime":"2019-04-02T08:19:37Z","updatedDatetime":"2019-04-02T08:54:42.497114599Z","lastReceivedDatetime":"2019-04-02T08:54:42.464955904Z","lastUsedChannelId":"1234","messages":{"totalCount":1,"href":"https://conversations.messagebird.com/v1/conversations/1234/messages"}}' data = { 'channelId': '1234', 'to': '+99999999999', 'type': "text", 'content': { 'text': 'Message Example' }, } msg = Client('', http_client).conversation_start(data) http_client.request.assert_called_once_with('conversations/start', 'POST', data) self.assertEqual('1234', msg.id) self.assertEqual(99999999999, msg.contact.msisdn) self.assertEqual(datetime(2019, 4, 2, 8, 19, 37, tzinfo=tzutc()), msg.contact.createdDatetime) self.assertEqual(datetime(2019, 4, 2, 8, 19, 38, tzinfo=tzutc()), msg.contact.updatedDatetime) self.assertEqual('channel-name', msg.channels[0].name)
Example #15
Source File: test_conversation_message.py From python-rest-api with BSD 2-Clause "Simplified" License | 6 votes |
def test_create_message(self): http_client = Mock() http_client.request.return_value = '{"id":"id","conversationId":"conversation-id","channelId":"channel-id","type":"text","content":{"text":"Example Text Message"},"direction":"sent","status":"pending","createdDatetime":"2019-04-02T11:57:52.142641447Z","updatedDatetime":"2019-04-02T11:57:53.142641447Z"}' data = { 'channelId': 1234, 'type': 'text', 'content': { 'text': 'this is a message' }, } msg = Client('', http_client).conversation_create_message('conversation-id', data) self.assertEqual(datetime(2019, 4, 2, 11, 57, 53, tzinfo=tzutc()), msg.updatedDatetime) self.assertEqual(datetime(2019, 4, 2, 11, 57, 52, tzinfo=tzutc()), msg.createdDatetime) http_client.request.assert_called_once_with('conversations/conversation-id/messages', 'POST', data)
Example #16
Source File: test_timestamp.py From vnpy_crypto with MIT License | 6 votes |
def test_class_ops_dateutil(self): def compare(x, y): assert (int(np.round(Timestamp(x).value / 1e9)) == int(np.round(Timestamp(y).value / 1e9))) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(tzutc())) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
Example #17
Source File: test_voice_recording.py From python-rest-api with BSD 2-Clause "Simplified" License | 6 votes |
def test_voice_recording_view(self): http_client = Mock() http_client.request.return_value = '{"data":[{"id":"12345678-9012-3456-7890-123456789012","format":"wav","legId":"87654321-0987-6543-2109-876543210987","status":"done","duration":32,"type":"transfer","createdAt":"2018-01-01T00:00:01Z","updatedAt":"2018-01-01T00:00:05Z","deletedAt":null}],"_links":{"file":"/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012.wav","self":"/calls/12345678-9012-3456-7890-123456789012/legs/12348765-4321-0987-6543-210987654321/recordings/12345678-9012-3456-7890-123456789012"},"pagination":{"totalCount":0,"pageCount":0,"currentPage":0,"perPage":0}}' voice_recording = Client('', http_client).voice_recording_view( '12348765-4321-0987-6543-210987654321', '87654321-0987-6543-2109-876543210987', '12345678-9012-3456-7890-123456789012' ) http_client.request.assert_called_once_with( 'https://voice.messagebird.com/calls/12348765-4321-0987-6543-210987654321/legs/87654321-0987-6543-2109-876543210987/recordings/12345678-9012-3456-7890-123456789012', 'GET', None) self.assertEqual('12345678-9012-3456-7890-123456789012', voice_recording.id) self.assertEqual('done', voice_recording.status) self.assertEqual('wav', voice_recording.format) self.assertEqual(datetime(2018, 1, 1, 0, 0, 1, tzinfo=tzutc()), voice_recording.createdAt) self.assertEqual(datetime(2018, 1, 1, 0, 0, 5, tzinfo=tzutc()), voice_recording.updatedAt) self.assertEqual(2, len(voice_recording._links)) self.assertIsInstance(str(voice_recording), str)
Example #18
Source File: isoparser.py From vnpy_crypto with MIT License | 6 votes |
def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants
Example #19
Source File: gcal.py From pkmeter with BSD 3-Clause "New" or "Revised" License | 6 votes |
def update(self): self.data['events'] = [] self.tzutc = tz.tzutc() self.tzlocal = tz.tzlocal() urls, colors = [], {} for cal in self._iter_calendars(): urls.append(cal.url) colors[cal.url] = cal.color for result in utils.iter_responses(urls, timeout=5): response = result.get('response') if response: ical = Calendar.from_ical(response.read().decode('utf-8')) color = colors[result.get('url')] self.data['events'] += self._parse_events(ical, color) self.data['events'] = sorted(self.data['events'], key=lambda e:e['start']) # Calculate time to next event now = datetime.datetime.now() next = [e for e in self.data['events'] if e['start'] > now][0]['start'] if self.data['events'] else self.DELTANONE if next < now + datetime.timedelta(seconds=self.DEFAULT_INTERVAL*1.5): self.data['next'] = 'Now' else: self.data['next'] = utils.natural_time(next-now, 1) super(Plugin, self).update()
Example #20
Source File: predicates.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 6 votes |
def check_reserved_batch_session( db_conn: SAConnection, sched_ctx: SchedulingContext, sess_ctx: PendingSession, ) -> PredicateResult: """ Check if a batch-type session should not be started for a certain amount of time. """ if sess_ctx.session_type == SessionTypes.BATCH: query = ( sa.select([kernels.c.starts_at]) .select_from(kernels) .where(kernels.c.id == sess_ctx.kernel_id) ) starts_at = await db_conn.scalar(query) if starts_at is not None and datetime.now(tzutc()) < starts_at: return PredicateResult( False, 'Before start time' ) return PredicateResult(True)
Example #21
Source File: isoparser.py From recruit with Apache License 2.0 | 6 votes |
def parse_tzstr(self, tzstr, zero_as_utc=True): """ Parse a valid ISO time zone string. See :func:`isoparser.isoparse` for details on supported formats. :param tzstr: A string representing an ISO time zone offset :param zero_as_utc: Whether to return :class:`dateutil.tz.tzutc` for zero-offset zones :return: Returns :class:`dateutil.tz.tzoffset` for offsets and :class:`dateutil.tz.tzutc` for ``Z`` and (if ``zero_as_utc`` is specified) offsets equivalent to UTC. """ return self._parse_tzstr(tzstr, zero_as_utc=zero_as_utc) # Constants
Example #22
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testInZoneFoldEquality(self): # Two datetimes in the same zone are considered to be equal if their # wall times are equal, even if they have different absolute times. tzname = 'Eastern Standard Time' args = self.get_args(tzname) with self.context(tzname): NYC = self.tzclass(*args) UTC = tz.tzutc() t_n, t0_u, t1_u = self.get_utc_transitions(NYC, 2011, False) dt0 = t_n.replace(tzinfo=NYC) dt1 = tz.enfold(dt0, fold=1) # Make sure these actually represent different times self.assertNotEqual(dt0.astimezone(UTC), dt1.astimezone(UTC)) # Test that they compare equal self.assertEqual(dt0, dt1) ### # Test Cases
Example #23
Source File: test_timestamp.py From recruit with Apache License 2.0 | 6 votes |
def test_class_ops_dateutil(self): def compare(x, y): assert (int(np.round(Timestamp(x).value / 1e9)) == int(np.round(Timestamp(y).value / 1e9))) compare(Timestamp.now(), datetime.now()) compare(Timestamp.now('UTC'), datetime.now(tzutc())) compare(Timestamp.utcnow(), datetime.utcnow()) compare(Timestamp.today(), datetime.today()) current_time = calendar.timegm(datetime.now().utctimetuple()) compare(Timestamp.utcfromtimestamp(current_time), datetime.utcfromtimestamp(current_time)) compare(Timestamp.fromtimestamp(current_time), datetime.fromtimestamp(current_time)) date_component = datetime.utcnow() time_component = (date_component + timedelta(minutes=10)).time() compare(Timestamp.combine(date_component, time_component), datetime.combine(date_component, time_component))
Example #24
Source File: test_imports.py From plugin.video.emby with GNU General Public License v3.0 | 6 votes |
def testTzAll(self): from dateutil.tz import tzutc from dateutil.tz import tzoffset from dateutil.tz import tzlocal from dateutil.tz import tzfile from dateutil.tz import tzrange from dateutil.tz import tzstr from dateutil.tz import tzical from dateutil.tz import gettz from dateutil.tz import tzwin from dateutil.tz import tzwinlocal from dateutil.tz import UTC from dateutil.tz import datetime_ambiguous from dateutil.tz import datetime_exists from dateutil.tz import resolve_imaginary tz_all = ["tzutc", "tzoffset", "tzlocal", "tzfile", "tzrange", "tzstr", "tzical", "gettz", "datetime_ambiguous", "datetime_exists", "resolve_imaginary", "UTC"] tz_all += ["tzwin", "tzwinlocal"] if sys.platform.startswith("win") else [] lvars = locals() for var in tz_all: self.assertIsNot(lvars[var], None)
Example #25
Source File: sqlstats.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def get_values(self, stats_key, start_timestamp=None, end_timestamp=None, date_strings=False): values = [] try: conditions = [MonitoringStats.stats_key == stats_key] if start_timestamp: utc_start_timestamp = convert_timestamp_to_utc(start_timestamp) conditions.append(MonitoringStats.timestamp >= utc_start_timestamp) if end_timestamp: utc_end_timestamp = convert_timestamp_to_utc(end_timestamp) conditions.append(MonitoringStats.timestamp <= utc_end_timestamp) for ms in MonitoringStats.query.filter(and_(*conditions)). \ order_by(MonitoringStats.timestamp.asc()): aware_timestamp = ms.timestamp.replace(tzinfo=tzutc()) values.append((aware_timestamp, ms.stats_value)) except Exception as exx: # pragma: no cover log.error(u"exception {0!r}".format(exx)) log.error(u"could not fetch list of keys") log.debug(u"{0!s}".format(traceback.format_exc())) self.session.rollback() finally: self.session.close() return values
Example #26
Source File: conftest.py From backend.ai-manager with GNU Lesser General Public License v3.0 | 5 votes |
def get_headers(app, default_keypair): def create_header(method, url, req_bytes, ctype='application/json', hash_type='sha256', api_version='v5.20191215', keypair=default_keypair): now = datetime.now(tzutc()) hostname = f"localhost:{app['config']['manager']['service-addr'].port}" headers = { 'Date': now.isoformat(), 'Content-Type': ctype, 'Content-Length': str(len(req_bytes)), 'X-BackendAI-Version': api_version, } if api_version >= 'v4.20181215': req_bytes = b'' else: if ctype.startswith('multipart'): req_bytes = b'' if ctype.startswith('multipart'): # Let aiohttp to create appropriate header values # (e.g., multipart content-type header with message boundaries) del headers['Content-Type'] del headers['Content-Length'] req_hash = hashlib.new(hash_type, req_bytes).hexdigest() sign_bytes = method.upper().encode() + b'\n' \ + url.encode() + b'\n' \ + now.isoformat().encode() + b'\n' \ + b'host:' + hostname.encode() + b'\n' \ + b'content-type:' + ctype.encode() + b'\n' \ + b'x-backendai-version:' + api_version.encode() + b'\n' \ + req_hash.encode() sign_key = hmac.new(keypair['secret_key'].encode(), now.strftime('%Y%m%d').encode(), hash_type).digest() sign_key = hmac.new(sign_key, hostname.encode(), hash_type).digest() signature = hmac.new(sign_key, sign_bytes, hash_type).hexdigest() headers['Authorization'] = \ f'BackendAI signMethod=HMAC-{hash_type.upper()}, ' \ + f'credential={keypair["access_key"]}:{signature}' return headers return create_header
Example #27
Source File: test_parser.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def test_tzlocal_parse_fold(): # One manifestion of GH #318 with TZEnvContext('EST+5EDT,M3.2.0/2,M11.1.0/2'): dt_exp = datetime(2011, 11, 6, 1, 30, tzinfo=tz.tzlocal()) dt_exp = tz.enfold(dt_exp, fold=1) dt = parse('2011-11-06T01:30 EST') # Because this is ambiguous, kuntil `tz.tzlocal() is tz.tzlocal()` # we'll just check the attributes we care about rather than # dt == dt_exp assert dt.tzname() == dt_exp.tzname() assert dt.replace(tzinfo=None) == dt_exp.replace(tzinfo=None) assert getattr(dt, 'fold') == getattr(dt_exp, 'fold') assert dt.astimezone(tz.tzutc()) == dt_exp.astimezone(tz.tzutc())
Example #28
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testUTCEquality(self): utc = tz.tzutc() o_utc = tz.tzoffset('UTC', 0) self.assertEqual(utc, o_utc) self.assertEqual(o_utc, utc)
Example #29
Source File: test_datetime.py From recruit with Apache License 2.0 | 5 votes |
def test_getitem_setitem_datetime_tz_dateutil(): from dateutil.tz import tzutc from pandas._libs.tslibs.timezones 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='America/New_York') 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('America/Chicago'))] = 0 result[datetime(1990, 1, 1, 3, tzinfo=tz('America/Chicago'))] = ts[4] assert_series_equal(result, ts)
Example #30
Source File: test_tz.py From plugin.video.emby with GNU General Public License v3.0 | 5 votes |
def testPickleTzUTC(self): self.assertPicklable(tz.tzutc(), singleton=True)