Python dateutil.parser.isoparse() Examples

The following are 30 code examples of dateutil.parser.isoparse(). 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.parser , or try the search function .
Example #1
Source File: news.py    From newspie with MIT License 6 votes vote down vote up
def parse_articles(response):
    ''' Parses articles fetched from News API.

    Returns:
        A list of dicts containing publishing date, title, URL and source of
        articles.
    '''
    parsed_articles = []
    if response.get('status') == 'ok':
        for article in response.get('articles'):
            parsed_articles.append({
                'published_at':
                    parser.isoparse(article['publishedAt']
                                   ).strftime('%Y-%m-%d %H:%M'),
                'title':
                    article['title'],
                'url':
                    article['url'],
                'source':
                    article['source']['name']
            })
    return parsed_articles 
Example #2
Source File: twistlock.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def report_license_expiration(self):
        service_check_name = "{}.license_ok".format(self.NAMESPACE)
        try:
            license = self._retrieve_json("/api/v1/settings/license")
            if "expiration_date" not in license:
                raise Exception("expiration_date not found.")
        except Exception as e:
            self.warning("cannot retrieve license data: %s", e)
            self.service_check(service_check_name, AgentCheck.CRITICAL, tags=self.config.tags)
            raise e

        # alert if your license will expire in 30 days and then in a week
        expiration_date = parser.isoparse(license.get("expiration_date"))
        current_date = datetime.now(tz.tzutc())
        warning_date = current_date + timedelta(days=30)
        critical_date = current_date + timedelta(days=7)

        licence_status = AgentCheck.OK
        if expiration_date < warning_date:
            licence_status = AgentCheck.WARNING
        if expiration_date < critical_date:
            licence_status = AgentCheck.CRITICAL
        self.service_check(
            service_check_name, licence_status, tags=self.config.tags, message=license.get("expiration_date")
        ) 
Example #3
Source File: reminders.py    From bot with MIT License 6 votes vote down vote up
def edit_reminder_content(self, ctx: Context, id_: int, *, content: str) -> None:
        """Edit one of your reminder's content."""
        # Send the request to update the reminder in the database
        reminder = await self.bot.api_client.patch(
            'bot/reminders/' + str(id_),
            json={'content': content}
        )

        # Parse the reminder expiration back into a datetime for the confirmation message
        expiration = isoparse(reminder['expiration']).replace(tzinfo=None)

        # Send a confirmation message to the channel
        await self._send_confirmation(
            ctx,
            on_success="That reminder has been edited successfully!",
            reminder_id=id_,
            delivery_dt=expiration,
        )
        await self._reschedule_reminder(reminder) 
Example #4
Source File: domain.py    From hcloud-python with MIT License 6 votes vote down vote up
def __init__(
            self,
            id,
            name=None,
            created=None,
            ip_range=None,
            subnets=None,
            routes=None,
            servers=None,
            protection=None,
            labels=None,
    ):
        self.id = id
        self.name = name
        self.created = isoparse(created) if created else None
        self.ip_range = ip_range
        self.subnets = subnets
        self.routes = routes
        self.servers = servers
        self.protection = protection
        self.labels = labels 
Example #5
Source File: domain.py    From hcloud-python with MIT License 6 votes vote down vote up
def __init__(
            self,
            id=None,
            name=None,
            certificate=None,
            not_valid_before=None,
            not_valid_after=None,
            domain_names=None,
            fingerprint=None,
            created=None,
            labels=None,
    ):
        self.id = id
        self.name = name
        self.certificate = certificate
        self.domain_names = domain_names
        self.fingerprint = fingerprint
        self.not_valid_before = isoparse(not_valid_before) if not_valid_before else None
        self.not_valid_after = isoparse(not_valid_after) if not_valid_after else None
        self.created = isoparse(created) if created else None
        self.labels = labels 
Example #6
Source File: strategy_systematic.py    From gs-quant with Apache License 2.0 6 votes vote down vote up
def check_underlier_fields(
            underlier: Union[EqOption, EqVarianceSwap]
    ) -> Union[EqOption, EqVarianceSwap]:
        # validation for different fields
        if isinstance(underlier.expiration_date, datetime.date):
            underlier = underlier.clone()
            underlier.expiration_date = '{}d'.format(
                (underlier.expiration_date - PricingContext.current.pricing_date).days)
        elif re.search(ISO_FORMAT, underlier.expiration_date) is not None:
            underlier = underlier.clone()
            underlier.expiration_date = '{}d'.format(
                (isoparse(underlier.expiration_date).date() - PricingContext.current.pricing_date).days)

        if isinstance(underlier, EqOption):
            underlier.number_of_options = None

        return underlier 
Example #7
Source File: test_isoparser.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def _isoparse_date_and_time(dt, date_fmt, time_fmt, tzoffset,
                            microsecond_precision=None):
    tzi, offset_str = tzoffset
    fmt = date_fmt + 'T' + time_fmt
    dt = dt.replace(tzinfo=tzi)
    dtstr = dt.strftime(fmt)

    if microsecond_precision is not None:
        if not fmt.endswith('%f'):
            raise ValueError('Time format has no microseconds!')

        if microsecond_precision != 6:
            dtstr = dtstr[:-(6 - microsecond_precision)]
        elif microsecond_precision > 6:
            raise ValueError('Precision must be 1-6')

    dtstr += offset_str

    assert isoparse(dtstr) == dt 
Example #8
Source File: wf_module.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def set_stored_data_version(
    workflow: Workflow, wf_module: WfModule, version: str, **kwargs
):
    try:
        # cast to str: dateutil.parser may have vulnerability with non-str
        version = str(version)
        version = isoparse(version)
    except (ValueError, OverflowError, TypeError):
        raise HandlerError("BadRequest: version must be an ISO8601 datetime")

    version = await _find_precise_version(wf_module, version)

    await commands.do(
        ChangeDataVersionCommand,
        workflow_id=workflow.id,
        wf_module=wf_module,
        new_version=version,
    )

    await _mark_stored_object_read(wf_module, version) 
Example #9
Source File: test_wf_module.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_stored_data_version(self):
        version = "2018-12-12T21:30:00.000Z"
        user = User.objects.create(username="a", email="a@example.org")
        workflow = Workflow.create_and_init(owner=user)
        wf_module = workflow.tabs.first().wf_modules.create(order=0, slug="step-1")
        wf_module.stored_objects.create(stored_at=isoparse(version), size=0)

        response = self.run_handler(
            set_stored_data_version,
            user=user,
            workflow=workflow,
            wfModuleId=wf_module.id,
            version=version,
        )
        self.assertResponse(response, data=None)
        wf_module.refresh_from_db()
        self.assertEqual(wf_module.stored_data_version, isoparse(version)) 
Example #10
Source File: test_wf_module.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_stored_data_version_microsecond_date(self):
        version_precise = "2018-12-12T21:30:00.000123Z"
        version_js = "2018-12-12T21:30:00.000Z"
        user = User.objects.create(username="a", email="a@example.org")
        workflow = Workflow.create_and_init(owner=user)
        wf_module = workflow.tabs.first().wf_modules.create(order=0, slug="step-1")
        # Postgres will store this with microsecond precision
        wf_module.stored_objects.create(stored_at=isoparse(version_precise), size=0)

        # JS may request it with millisecond precision
        response = self.run_handler(
            set_stored_data_version,
            user=user,
            workflow=workflow,
            wfModuleId=wf_module.id,
            version=version_js,
        )
        self.assertResponse(response, data=None)
        wf_module.refresh_from_db()
        self.assertEqual(wf_module.stored_data_version, isoparse(version_precise)) 
Example #11
Source File: test_wf_module.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_set_stored_data_version_command_set_read(self):
        version = "2018-12-12T21:30:00.000Z"
        user = User.objects.create(username="a", email="a@example.org")
        workflow = Workflow.create_and_init(owner=user)
        wf_module = workflow.tabs.first().wf_modules.create(order=0, slug="step-1")
        so = wf_module.stored_objects.create(
            stored_at=isoparse(version), size=0, read=False
        )

        response = self.run_handler(
            set_stored_data_version,
            user=user,
            workflow=workflow,
            wfModuleId=wf_module.id,
            version=version,
        )
        self.assertResponse(response, data=None)
        so.refresh_from_db()
        self.assertEqual(so.read, True) 
Example #12
Source File: test_client.py    From hcloud-python with MIT License 5 votes vote down vote up
def test_bound_network_init(self, network_response):
        bound_network = BoundNetwork(
            client=mock.MagicMock(),
            data=network_response['network']
        )

        assert bound_network.id == 1
        assert bound_network.created == isoparse("2016-01-30T23:50:11+00:00")
        assert bound_network.name == "mynet"
        assert bound_network.ip_range == "10.0.0.0/16"
        assert bound_network.protection['delete'] is False

        assert len(bound_network.servers) == 1
        assert isinstance(bound_network.servers[0], BoundServer)
        assert bound_network.servers[0].id == 42
        assert bound_network.servers[0].complete is False

        assert len(bound_network.subnets) == 2
        assert isinstance(bound_network.subnets[0], NetworkSubnet)
        assert bound_network.subnets[0].type == "cloud"
        assert bound_network.subnets[0].ip_range == "10.0.1.0/24"
        assert bound_network.subnets[0].network_zone == "eu-central"
        assert bound_network.subnets[0].gateway == "10.0.0.1"

        assert len(bound_network.routes) == 1
        assert isinstance(bound_network.routes[0], NetworkRoute)
        assert bound_network.routes[0].destination == "10.100.1.0/24"
        assert bound_network.routes[0].gateway == "10.0.1.1" 
Example #13
Source File: serialize.py    From sdk-codegen with MIT License 5 votes vote down vote up
def datetime_structure_hook(d: str, t: datetime.datetime) -> datetime.datetime:
        return parser.isoparse(d) 
Example #14
Source File: test_domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def __init__(self, id, name="name1", started=None):
        self.id = id
        self.name = name
        self.started = isoparse(started) if started else None 
Example #15
Source File: domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def __init__(
        self,
        id=None,
        name=None,
        type=None,
        description=None,
        deprecated=None,
    ):
        self.id = id
        self.name = name
        self.type = type
        self.description = description
        self.deprecated = isoparse(deprecated) if deprecated else None 
Example #16
Source File: domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            id,
            name=None,
            server=None,
            created=None,
            location=None,
            size=None,
            linux_device=None,
            format=None,
            protection=None,
            labels=None,
            status=None

    ):
        self.id = id
        self.name = name
        self.server = server
        self.created = isoparse(created) if created else None
        self.location = location
        self.size = size
        self.linux_device = linux_device
        self.format = format
        self.protection = protection
        self.labels = labels
        self.status = status 
Example #17
Source File: domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            id,
            name=None,
            status=None,
            created=None,
            public_net=None,
            server_type=None,
            datacenter=None,
            image=None,
            iso=None,
            rescue_enabled=None,
            locked=None,
            backup_window=None,
            outgoing_traffic=None,
            ingoing_traffic=None,
            included_traffic=None,
            protection=None,
            labels=None,
            volumes=None,
            private_net=None,
    ):
        self.id = id
        self.name = name
        self.status = status
        self.created = isoparse(created) if created else None
        self.public_net = public_net
        self.server_type = server_type
        self.datacenter = datacenter
        self.image = image
        self.iso = iso
        self.rescue_enabled = rescue_enabled
        self.locked = locked
        self.backup_window = backup_window
        self.outgoing_traffic = outgoing_traffic
        self.ingoing_traffic = ingoing_traffic
        self.included_traffic = included_traffic
        self.protection = protection
        self.labels = labels
        self.volumes = volumes
        self.private_net = private_net 
Example #18
Source File: domain.py    From hcloud-python with MIT License 5 votes vote down vote up
def __init__(
            self,
            id=None,
            name=None,
            type=None,
            created=None,
            description=None,
            image_size=None,
            disk_size=None,
            deprecated=None,
            bound_to=None,
            os_flavor=None,
            os_version=None,
            rapid_deploy=None,
            created_from=None,
            protection=None,
            labels=None,
            status=None

    ):
        self.id = id
        self.name = name
        self.type = type
        self.created = isoparse(created) if created else None
        self.description = description
        self.image_size = image_size
        self.disk_size = disk_size
        self.deprecated = isoparse(deprecated) if deprecated else None
        self.bound_to = bound_to
        self.os_flavor = os_flavor
        self.os_version = os_version
        self.rapid_deploy = rapid_deploy
        self.created_from = created_from
        self.protection = protection
        self.labels = labels
        self.status = status 
Example #19
Source File: _converters.py    From azure-kusto-python with MIT License 5 votes vote down vote up
def to_datetime(value):
    """Converts a string to a datetime."""
    if isinstance(value, int):
        return parser.parse(value)
    return parser.isoparse(value) 
Example #20
Source File: test_wf_module.py    From cjworkbench with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_set_stored_data_version_viewer_access_denied(self):
        version = "2018-12-12T21:30:00.000Z"
        workflow = Workflow.create_and_init(public=True)
        wf_module = workflow.tabs.first().wf_modules.create(order=0, slug="step-1")
        wf_module.stored_objects.create(stored_at=isoparse(version), size=0)

        response = self.run_handler(
            set_stored_data_version,
            workflow=workflow,
            wfModuleId=wf_module.id,
            version=version,
        )
        self.assertResponse(response, error="AuthError: no write access to workflow") 
Example #21
Source File: blocks.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def decode(self, value):
        if value:
            return isoparse(value) 
Example #22
Source File: knowledge.py    From connectors with Apache License 2.0 5 votes vote down vote up
def _parse_timestamp(self, ts: str) -> str:
        try:
            return dp.isoparse(ts).strftime("%Y-%m-%dT%H:%M:%S+00:00")
        except ValueError:
            self._error("error parsing ts: ", ts)
            return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00") 
Example #23
Source File: models.py    From connectors with Apache License 2.0 5 votes vote down vote up
def date(self) -> str:
        """Malpedia yara date."""
        extract = re.search(r"([0-9]{4}\-[0-9]{2}\-[0-9]{2})", self.raw_rule)
        if extract is None:
            return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00")
        else:
            try:
                return dp.isoparse(extract.group(1)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
            except Exception:
                return datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00") 
Example #24
Source File: TwitchSource.py    From Dozer with GNU General Public License v3.0 5 votes vote down vote up
def generate_embed(self, data, games):
        """Given data on a stream and a dict of games, assemble an embed"""
        try:
            display_name = data['display_name']
        except KeyError:
            display_name = data['user_name']

        embed = discord.Embed()
        embed.title = f"{display_name} is now live on Twitch!"
        embed.colour = self.color

        embed.description = data['title']

        embed.url = f"https://www.twitch.tv/{data['user_name']}"

        embed.add_field(name="Playing", value=games[data['game_id']], inline=True)
        embed.add_field(name="Watching", value=data['viewer_count'], inline=True)

        embed.set_author(name=display_name, url=embed.url, icon_url=self.users[data['user_id']].profile_image_url)

        embed.set_image(url=data['thumbnail_url'].format(width=1920, height=1080))

        start_time = parser.isoparse(data['started_at'])
        embed.timestamp = start_time

        return embed 
Example #25
Source File: utils.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def date_to_ts(iso_string):
    # type: (str) -> int
    return int((parser.isoparse(iso_string) - datetime(1970, 1, 1, tzinfo=tz.UTC)).total_seconds()) 
Example #26
Source File: twistlock.py    From integrations-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _report_service_check(self, data, prefix, tags=None, message=""):
        # Last scan service check
        scan_date = parser.isoparse(data.get("scanTime"))
        scan_status = AgentCheck.OK
        if scan_date < self.warning_date:
            scan_status = AgentCheck.WARNING
        if scan_date < self.critical_date:
            scan_status = AgentCheck.CRITICAL
        self.service_check('{}.is_scanned'.format(prefix), scan_status, tags=tags, message=message) 
Example #27
Source File: test_isoparser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def test_iso_ordinal(isoord, dt_expected):
    for fmt in ('{:04d}-{:03d}', '{:04d}{:03d}'):
        dtstr = fmt.format(*isoord)

        assert isoparse(dtstr) == dt_expected


###
# Acceptance of bytes 
Example #28
Source File: reminders.py    From bot with MIT License 5 votes vote down vote up
def _scheduled_task(self, reminder: dict) -> None:
        """A coroutine which sends the reminder once the time is reached, and cancels the running task."""
        reminder_id = reminder["id"]
        reminder_datetime = isoparse(reminder['expiration']).replace(tzinfo=None)

        # Send the reminder message once the desired duration has passed
        await wait_until(reminder_datetime)
        await self.send_reminder(reminder)

        log.debug(f"Deleting reminder {reminder_id} (the user has been reminded).")
        await self._delete_reminder(reminder_id) 
Example #29
Source File: test_isoparse_prop.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def test_timespec_auto(dt, sep):
    if dt.tzinfo is not None:
        # Assume offset has no sub-second components
        assume(dt.utcoffset().total_seconds() % 60 == 0)

    sep = str(sep)          # Python 2.7 requires bytes
    dtstr = dt.isoformat(sep=sep)
    dt_rt = isoparse(dtstr)

    assert dt_rt == dt 
Example #30
Source File: test_isoparser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def test_year_only(dt):
    dtstr = dt.strftime('%Y')

    assert isoparse(dtstr) == dt