Example #1
0
def _truncate_date_value_according_on_date_field(field, date_value):
    """Truncates date value (to year only) according to the given date field.

    Args:
        field (unicode): The field for which the date value will be used to query on.
        date_value (str): The date value that is going to be truncated to its year.

    Returns:
        PartialDate: The possibly truncated date, on success. None, otherwise.

    Notes:
        In case the fieldname is in `ES_MAPPING_HEP_DATE_ONLY_YEAR`, then the date is normalized and then only its year
        value is used. This is needed for ElasticSearch to be able to do comparisons on dates that have only year, which
        fails if being queried with a date with more .
    """
    try:
        partial_date = PartialDate.parse(date_value)
    except ValueError:
        return None

    if field in ES_MAPPING_HEP_DATE_ONLY_YEAR:
        truncated_date = PartialDate.from_parts(partial_date.year)
    else:
        truncated_date = partial_date

    return truncated_date
Example #2
0
def test_partial_date_pprints_correct_date():
    expected_full = 'Jan 1, 1890'
    expected_no_day = 'Jan, 1890'
    expected_no_month = '1890'

    assert expected_full == PartialDate(1890, 1, 1).pprint()
    assert expected_no_day == PartialDate(1890, 1).pprint()
    assert expected_no_month == PartialDate(1890).pprint()
Example #3
0
 def publication_date(self):
     publication_date = None
     publication_date_string = self.root.xpath(
         "string(./RDF/Description/coverDisplayDate[1])").extract_first()
     if publication_date_string:
         try:
             publication_date = PartialDate.parse(publication_date_string)
         except:
             # in case when date contains month range, eg. July-September 2020
             publication_date = re.sub("[A-aZ-z]*-(?=[A-aZ-z])", "",
                                       publication_date_string)
             publication_date = PartialDate.parse(publication_date)
     return publication_date
Example #4
0
    def imprints(self):
        '''issued: Eariest of published-print and published-online

        That is why we use this field to fill the imprints and the publication info.
        '''

        date_parts = get_value(self.record, "issued.date-parts[0]")

        if not date_parts:
            return None

        date = PartialDate(*date_parts)

        return date.dumps()
Example #5
0
 def _get_datetime(value):
     d_value = force_single_element(value.get('d', ''))
     if d_value:
         try:
             date = PartialDate.loads(d_value)
         except ValueError:
             return d_value
         else:
             datetime_ = datetime(year=date.year, month=date.month, day=date.day)
             return datetime_.isoformat()
Example #6
0
    def publication_date(self):
        """(Partial) date of publication.

        Returns:
            partial_date (inspire_utils.date.PartialDate): publication date
        """
        try:
            return PartialDate.loads(get_value(self.record, 'imprints.date[0]') or get_publication_date(self.record))
        except ValueError:
            return None
Example #7
0
    def publication_date(self):
        """(Partial) date of publication.

        Returns:
            partial_date (inspire_utils.date.PartialDate): publication date
        """
        try:
            return PartialDate.loads(
                get_value(self.record, "imprints.date[0]")
                or LiteratureReader(self.record).publication_date)
        except ValueError:
            return None
Example #8
0
    def publication_date(self):
        """(Partial) date of publication.

        Returns:
            partial_date (inspire_utils.date.PartialDate): publication date
        """
        try:
            return PartialDate.loads(
                get_value(self.record, 'imprints.date[0]')
                or get_publication_date(self.record))
        except ValueError:
            return None
Example #9
0
    def get_date(date_node):
        """Extract a date from a date node.

        Returns:
            PartialDate: the parsed date.
        """
        iso_string = date_node.xpath('./@iso-8601-date').extract_first()
        iso_date = PartialDate.loads(iso_string) if iso_string else None

        year = date_node.xpath('string(./year)').extract_first()
        month = date_node.xpath('string(./month)').extract_first()
        day = date_node.xpath('string(./day)').extract_first()
        date_from_parts = PartialDate.from_parts(year, month, day) if year else None

        string_date = date_node.xpath('string(./string-date)').extract_first()
        try:
            parsed_date = PartialDate.parse(string_date)
        except ValueError:
            parsed_date = None

        date = get_first([iso_date, date_from_parts, parsed_date])
        return date
Example #10
0
    def get_date(data, doc_type):
        publication_year = BibTexCommonSchema.get_best_publication_info(
            data).get("year")
        thesis_date = get_value(data, "thesis_info.date")
        imprint_date = get_value(data, "imprints.date[0]")

        if doc_type.endswith("thesis"):
            date_choice = thesis_date or publication_year or imprint_date
        else:
            date_choice = publication_year or thesis_date or imprint_date

        if date_choice:
            return PartialDate.loads(str(date_choice))
Example #11
0
    def get_date(date_node):
        """Extract a date from a date node.

        Returns:
            PartialDate: the parsed date.
        """
        iso_string = date_node.xpath('./@iso-8601-date').extract_first()
        iso_date = PartialDate.loads(iso_string) if iso_string else None

        year = date_node.xpath('string(./year)').extract_first()
        month = date_node.xpath('string(./month)').extract_first()
        day = date_node.xpath('string(./day)').extract_first()
        date_from_parts = PartialDate.from_parts(year, month, day) if year else None

        string_date = date_node.xpath('string(./string-date)').extract_first()
        try:
            parsed_date = PartialDate.parse(string_date)
        except ValueError:
            parsed_date = None

        date = get_first([iso_date, date_from_parts, parsed_date])
        return date
def test_add_publication_date():
    expected = xml_parse("""
    <work:work xmlns:common="http://www.orcid.org/ns/common" xmlns:work="http://www.orcid.org/ns/work">
        <common:publication-date>
            <common:year>1996</common:year>
            <common:month>09</common:month>
            <common:day>07</common:day>
        </common:publication-date>
    </work:work>
    """)

    builder = OrcidBuilder()
    builder.add_publication_date(PartialDate(1996, 9, 7))
    result = builder.get_xml()

    assert xml_compare(result, expected)
Example #13
0
    def get_date(data, doc_type):

        publication_year = BibTexCommonSchema.get_best_publication_info(
            data).get("year")
        thesis_date = get_value(data, "thesis_info.date")
        imprint_date = get_value(data, "imprints.date[0]")
        earliest_date = data.earliest_date
        date_map = {
            "mastersthesis": thesis_date,
            "phdthesis": thesis_date,
            "book": imprint_date,
            "inbook": imprint_date,
        }
        date_choice = date_map.get(
            doc_type) or publication_year or earliest_date
        if date_choice:
            return PartialDate.loads(str(date_choice))
Example #14
0
def get_date(data, doc_type):
    """Return a publication/thesis/imprint date.

    Args:
      data (dict): INSPIRE literature record to be serialized
      doc_type (text_type): BibTeX document type, as reported by `bibtex_document_type`

    Returns:
        PartialDate: publication date for a record.
    """
    publication_year = get_best_publication_info(data).get('year')
    thesis_date = get_value(data, 'thesis_info.date')
    imprint_date = get_value(data, 'imprints.date[0]')

    if doc_type.endswith('thesis'):
        date_choice = thesis_date or publication_year or imprint_date
    else:
        date_choice = publication_year or thesis_date or imprint_date

    if date_choice:
        return PartialDate.loads(str(date_choice))
Example #15
0
def get_date(data, doc_type):
    """Return a publication/thesis/imprint date.

    Args:
      data (dict): INSPIRE literature record to be serialized
      doc_type (text_type): BibTeX document type, as reported by `bibtex_document_type`

    Returns:
        PartialDate: publication date for a record.
    """
    publication_year = get_best_publication_info(data).get('year')
    thesis_date = get_value(data, 'thesis_info.date')
    imprint_date = get_value(data, 'imprints.date[0]')

    if doc_type.endswith('thesis'):
        date_choice = thesis_date or publication_year or imprint_date
    else:
        date_choice = publication_year or thesis_date or imprint_date

    if date_choice:
        return PartialDate.loads(str(date_choice))
Example #16
0
def _get_next_date_from_partial_date(partial_date):
    """Calculates the next date from the given partial date.

    Args:
        partial_date (inspire_utils.date.PartialDate): The partial date whose next date should be calculated.

    Returns:
        PartialDate: The next date from the given partial date.
    """
    relativedelta_arg = 'years'

    if partial_date.month:
        relativedelta_arg = 'months'
    if partial_date.day:
        relativedelta_arg = 'days'

    next_date = parse(
        partial_date.dumps()) + relativedelta(**{relativedelta_arg: 1})
    return PartialDate.from_parts(
        next_date.year, next_date.month if partial_date.month else None,
        next_date.day if partial_date.day else None)
Example #17
0
 def _get_work_priority_tuple(work):
     start_date = work.get('start_date')
     return (
         work.get('current'),
         PartialDate.parse(start_date) if start_date else EARLIEST_DATE,
     )
Example #18
0
def test_partial_date_pprints_when_cast_to_str():
    expected = 'Jun, 1686'

    assert expected == str(PartialDate(1686, 6))
Example #19
0
def test_partial_date_from_parts():
    expected = PartialDate(1686, 6)

    assert expected == PartialDate.from_parts(1686, 'June')
Example #20
0
def test_partial_date_loads():
    expected = PartialDate(1686, 6)

    assert expected == PartialDate.loads('1686-06')
Example #21
0
def test_loads_validate_dates_month():
    with pytest.raises(ValueError):
        PartialDate.loads('2015-1-10')
Example #22
0
def test_partial_date_self_inequality():
    date = PartialDate(1686)

    assert not date < date
Example #23
0
# or submit itself to any jurisdiction.
"""Author builder class and related code."""

from __future__ import absolute_import, division, print_function

from inspire_utils.date import normalize_date, PartialDate
from inspire_utils.helpers import force_list
from inspire_utils.name import normalize_name
from inspire_utils.record import get_value

from ..utils import EMPTIES, filter_empty_parameters, load_schema

RANKS = load_schema('elements/rank')['enum']
RANKS.append(None)
INSTITUTION_RANK_TO_PRIORITY = {rank: -idx for (idx, rank) in enumerate(RANKS)}
EARLIEST_DATE = PartialDate.loads('1000')


class AuthorBuilder(object):
    """Author record builder."""
    def __init__(self, author=None, source=None):
        if author is None:
            author = {
                '_collections': ['Authors'],
            }
        self.obj = author
        self.source = source

    def _ensure_field(self, field_name, value):
        if field_name not in self.obj:
            self.obj[field_name] = value
Example #24
0
def test_partial_date_raises_on_wrong_types():
    with pytest.raises(TypeError):
        PartialDate('1686', '6', '30')
Example #25
0
def test_partial_date_raises_on_day_with_no_month():
    with pytest.raises(TypeError):
        PartialDate(1686, None, 30)
Example #26
0
def test_partial_date_raises_on_invalid_dates():
    with pytest.raises(ValueError):
        PartialDate(1686, 1, 42)
Example #27
0
def test_partial_date_accepts_valid_dates():
    PartialDate(1686, 6, 30)
Example #28
0
def test_loads_validate_dates_day():
    with pytest.raises(ValueError):
        PartialDate.loads('2015-10-1')
Example #29
0
def test_partial_date_sorts_incomplete_dates_after_complete_dates():
    complete = PartialDate(1686, 6, 30)
    incomplete = PartialDate(1686)

    assert complete < incomplete
    assert not incomplete < complete
Example #30
0
def test_partial_date_equality():
    assert PartialDate(1686, 6) == PartialDate(1686, 6)
Example #31
0
def test_loads_validate_dates_month_when_month_is_00():
    with pytest.raises(ValueError):
        PartialDate.loads('2015-00')