Python datetime.datetime.date() Examples

The following are code examples for showing how to use datetime.datetime.date(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 7 votes vote down vote up
def isoformat(self, sep='T'):
        """
        Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
        date and time portions

        :param set:
            A single character of the separator to place between the date and
            time

        :return:
            The formatted datetime as a unicode string in Python 3 and a byte
            string in Python 2
        """

        if self.microsecond == 0:
            return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
        return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep) 
Example 2
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 6 votes vote down vote up
def loan_item(self, **kwargs):
        """Loan item to the user.

        Adds a loan to *_circulation.holdings*.

        :param user: Invenio-Accounts user.
        :param start_date: Start date of the loan. Must be today.
        :param end_date: End date of the loan.
        :param waitlist: If the desired dates are not available, the item will
                         be put on a waitlist.
        :param delivery: 'pickup' or 'mail'
        """
        id = str(uuid4())
        self['_circulation']['status'] = ItemStatus.ON_LOAN
        holdings = self.holdings
        if holdings and \
           holdings[0]['patron_barcode'] == kwargs.get('patron_barcode'):
            self.holdings.pop(0)
        self.holdings.insert(0, Holding.create(id=id, **kwargs))
        CircTransaction.create(self.build_data(0, 'add_item_loan'), id=id) 
Example 3
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 6 votes vote down vote up
def extend_loan(
            self, requested_end_date=None, renewal_count=None, **kwargs
    ):
        """Request a new end date for the active loan.

        A possible status ItemStatus.OVERDUE will be removed.
        """
        id = str(uuid4())
        if not renewal_count:
            renewal_count = self.get_renewal_count() + 1
        if not requested_end_date:
            request_date = datetime.today() + timedelta(self.duration)
            requested_end_date = datetime.strftime(request_date, '%Y-%m-%d')
        self.holdings[0]['end_date'] = requested_end_date
        self.holdings[0]['renewal_count'] = renewal_count
        CircTransaction.create(self.build_data(0, 'extend_item_loan'), id=id) 
Example 4
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 6 votes vote down vote up
def strftime(self, format):
        """
        Formats the date using strftime()

        :param format:
            The strftime() format string

        :return:
            The formatted date as a unicode string in Python 3 and a byte
            string in Python 2
        """

        output = self._format(format)
        if py2:
            return output.encode('utf-8')
        return output 
Example 5
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 6 votes vote down vote up
def strftime(self, format):
        """
        Formats the date using strftime()

        :param format:
            The strftime() format string

        :return:
            The formatted date as a unicode string in Python 3 and a byte
            string in Python 2
        """

        output = self._format(format)
        if py2:
            return output.encode('utf-8')
        return output 
Example 6
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 7
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 8
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 6 votes vote down vote up
def __deserialize_date(self, string):
        """
        Deserializes string to date.

        :param string: str.
        :return: date.
        """
        try:
            from dateutil.parser import parse
            return parse(string).date()
        except ImportError:
            return string
        except ValueError:
            raise ApiException(
                status=0,
                reason="Failed to parse `{0}` into a date object".format(string)
            ) 
Example 9
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 10
Project: sic   Author: Yanixos   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 11
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 12
Project: bigquerylayers   Author: smandaric   File: pyparsing.py    GNU General Public License v3.0 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 13
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 14
Project: AshsSDK   Author: thehappydinoa   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 15
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 6 votes vote down vote up
def get_most_recent_artifact(self):
        """
        Returns the most recent artifact (publication, talk, or video) as tuple of (date, artifact)
        :return: the most recent artifact, a tuple of (date, artifact)
        """
        mostRecentArtifacts = []

        if self.publication_set.exists():
            mostRecentPub = self.publication_set.order_by('-date')[0]
            mostRecentArtifacts.append((mostRecentPub.date, mostRecentPub))

        if self.talk_set.exists():
            mostRecentTalk = self.talk_set.order_by('-date')[0]
            mostRecentArtifacts.append((mostRecentTalk.date, mostRecentTalk))

        if self.video_set.exists():
            mostRecentVideo = self.video_set.order_by('-date')[0]
            mostRecentArtifacts.append((mostRecentVideo.date, mostRecentVideo))

        if len(mostRecentArtifacts) > 0:
            mostRecentArtifacts = sorted(mostRecentArtifacts, key=lambda artifact: artifact[0], reverse=True)
            return mostRecentArtifacts[0][0], mostRecentArtifacts[0][1]
        else:
            return None 
Example 16
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 6 votes vote down vote up
def update_file_name_poster(sender, instance, action, reverse, **kwargs):
    # Reverse: Indicates which side of the relation is updated (i.e., if it is the forward or reverse relation that is being modified)
    # Action: A string indicating the type of update that is done on the relation.
    # post_add: Sent after one or more objects are added to the relation
    if action == 'post_add' and not reverse:
        initial_path = instance.pdf_file.path
        person = instance.get_person()
        name = person.last_name
        year = instance.date.year
        title = ''.join(x for x in instance.title.title() if not x.isspace())
        title = ''.join(e for e in title if e.isalnum())


        #change the path of the pdf file to point to the new file name
        instance.pdf_file.name = os.path.join('posters', name + '_' + title + '_' + str(year) + '.pdf')
        new_path = os.path.join(settings.MEDIA_ROOT, instance.pdf_file.name)
        os.rename(initial_path, new_path)
        instance.save() 
Example 17
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 6 votes vote down vote up
def get_citation_as_html(self):
        """Returns a human readable citation as html"""
        citation = ""
        author_idx = 0
        num_authors = self.authors.count()
        for author in self.authors.all():
            citation += author.get_citation_name(full_name=False)

            if (author_idx + 1) < num_authors:
                citation += ", "
            else:
                citation += " "

            author_idx += 1

        citation += "({}). ".format(self.date.year)
        citation += self.title + ". "
        citation += "<i>{}</i>. ".format(self.book_title_short)

        if self.official_url:
            citation += "<a href={}>{}</a>".format(self.official_url, self.official_url)

        return citation 
Example 18
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 6 votes vote down vote up
def get_bibtex_id(self):
        """Generates and returns the bibtex id for this paper"""
        bibtex_id = self.get_person().last_name

        forum = self.book_title_short.lower()
        if "proceedings of" in forum:
            forum = forum.replace('proceedings of', '')

        forum = forum.upper().replace(" ", "")
        if not forum[-1].isdigit():
            forum = forum + str(self.date.year)

        bibtex_id += ":" + forum

        # code to make acronym from: https://stackoverflow.com/a/4355337
        title_acronym = ''.join(w[0] for w in self.title.split() if w[0].isupper())
        bibtex_id += ":" + title_acronym[:3]

        if self.doi:
            doi = self.doi.rsplit('/', 1)[-1]
            bibtex_id += doi

        bibtex_id += ","

        return bibtex_id 
Example 19
Project: Repobot   Author: Desgard   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 20
Project: Repobot   Author: Desgard   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 21
Project: Aegis   Author: jlillywh   File: time_series.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, values_name='values', start_date='1/1/19', periods=365):
        """Initialize with values of zero for the duration and frequency.
        
            Parameters
            ----------
            date_range : pandas DatetimeIndex
            Represents the date range for the time series
            Must be used to provide the index list for the values"""
        _start_date = datetime.strptime(start_date, '%x').date()
        self.date_rng = pd.date_range(start=start_date, periods=periods)
        self.values_name = values_name
        # self.df = pd.DataFrame({date': [_start_date + timedelta(days=x) for x in range(periods)], self.values_name: pd.Series(np.random.randn(periods))})
        # self.df = self.df.set_index('date')
        self.df = pd.DataFrame(self.date_rng, columns=['date'])
        self.df[values_name] = np.random.randint(0, 100, size=len(self.date_rng))
        self.df['datetime'] = pd.to_datetime(self.df['date'])
        self.df = self.df.set_index('datetime')
        self.df.drop(['date'], axis=1, inplace=True)
        
        # self.date_range = pd.date_range(start_date, periods=periods, freq=freq)
        # np.random.seed(seed=1111)
        # self.data = np.random.randint(1, high=100, size=len(self.date_range))
        # self.df = pd.DataFrame({'Date': self.date_range, 'Values': self.data})
        # self.df.set_index('Date') 
Example 22
Project: JukeBox   Author: gauravsarkar97   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 23
Project: year2018   Author: baijiangliang   File: repository.py    MIT License 6 votes vote down vote up
def get_commit_stat_by_day(self) -> Dict[datetime.date, Dict[str, Any]]:
        """ Get each day's commit stat. """
        commits = {}
        for repo in self.repos:
            for commit in repo.user_commits:
                commit_day = util.timestamp_to_datetime(commit.timestamp).date()
                if commit_day not in commits:
                    commits[commit_day] = {
                        'commits': [commit],
                        'insert': commit.code_ins,
                        'delete': commit.code_del,
                    }
                else:
                    commits[commit_day]['commits'].append(commit)
                    commits[commit_day]['insert'] += commit.code_ins
                    commits[commit_day]['delete'] += commit.code_del
        for day, stat in commits.items():
            weight = weight_commits(len(stat['commits']), stat['insert'], stat['delete'])
            commits[day]['weight'] = weight
        return commits 
Example 24
Project: Health-Checker   Author: KriAga   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 25
Project: Health-Checker   Author: KriAga   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 26
Project: qfit-3.0   Author: ExcitedStates   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})

        Example::
            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))
        prints::
            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s,l,t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 27
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: pyparsing.py    MIT License 6 votes vote down vote up
def convertToDate(fmt="%Y-%m-%d"):
        """
        Helper to create a parse action for converting parsed date string to Python datetime.date

        Params -
         - fmt - format to be passed to datetime.strptime (default= ``"%Y-%m-%d"``)

        Example::

            date_expr = pyparsing_common.iso8601_date.copy()
            date_expr.setParseAction(pyparsing_common.convertToDate())
            print(date_expr.parseString("1999-12-31"))

        prints::

            [datetime.date(1999, 12, 31)]
        """
        def cvt_fn(s, l, t):
            try:
                return datetime.strptime(t[0], fmt).date()
            except ValueError as ve:
                raise ParseException(s, l, str(ve))
        return cvt_fn 
Example 28
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 6 votes vote down vote up
def apply(self, other):
        # Timestamp can handle tz and nano sec, thus no need to use apply_wraps
        if isinstance(other, Timestamp):

            # GH 15126
            # in order to avoid a recursive
            # call of __add__ and __radd__ if there is
            # an exception, when we call using the + operator,
            # we directly call the known method
            result = other.__add__(self)
            if result is NotImplemented:
                raise OverflowError
            return result
        elif isinstance(other, (datetime, np.datetime64, date)):
            return as_timestamp(other) + self

        if isinstance(other, timedelta):
            return other + self.delta
        elif isinstance(other, type(self)):
            return type(self)(self.n + other.n)

        raise ApplyTypeError(
            "Unhandled type: {type_str}".format(type_str=type(other).__name__)
        ) 
Example 29
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def request_item(self, **kwargs):
        """Request item for the user.

        Adds a request to *_circulation.holdings*.

        :param user: Invenio-Accounts user.
        :param request_datetime: Start date of the loan.
                                 Must be today or a future date.
        :param waitlist: If the desired dates are not available, the item will
                         be put on a waitlist.
        :param delivery: 'pickup' or 'mail'
        """
        id = str(uuid4())
        self.holdings.append(Holding.create(id=id, **kwargs))
        CircTransaction.create(self.build_data(-1, 'add_item_request'), id=id) 
Example 30
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 5 votes vote down vote up
def get_item_end_date(self):
        """Get item due date a given item."""
        circulation = self.get('_circulation', {})
        if circulation:
            holdings = circulation.get('holdings', [])
            if holdings:
                if self.status == ItemStatus.ON_LOAN:
                    if holdings[0].get('end_date'):
                        end_date_str = holdings[0].get('end_date')
                        end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
                        return end_date
        return None 
Example 31
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def _format(self, format):
        """
        Performs strftime(), always returning a unicode string

        :param format:
            A strftime() format string

        :return:
            A unicode string of the formatted date
        """

        format = format.replace('%Y', '0000')
        # Year 0 is 1BC and a leap year. Leap years repeat themselves
        # every 28 years. Because of adjustments and the proleptic gregorian
        # calendar, the simplest way to format is to substitute year 2000.
        temp = date(2000, self.month, self.day)
        if '%c' in format:
            c_out = temp.strftime('%c')
            # Handle full years
            c_out = c_out.replace('2000', '0000')
            c_out = c_out.replace('%', '%%')
            format = format.replace('%c', c_out)
        if '%x' in format:
            x_out = temp.strftime('%x')
            # Handle formats such as 08/16/2000 or 16.08.2000
            x_out = x_out.replace('2000', '0000')
            x_out = x_out.replace('%', '%%')
            format = format.replace('%x', x_out)
        return temp.strftime(format) 
Example 32
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def isoformat(self):
        """
        Formats the date as %Y-%m-%d

        :return:
            The date formatted to %Y-%m-%d as a unicode string in Python 3
            and a byte string in Python 2
        """

        return self.strftime('0000-%m-%d') 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def replace(self, year=None, month=None, day=None):
        """
        Returns a new datetime.date or asn1crypto.util.extended_date
        object with the specified components replaced

        :return:
            A datetime.date or asn1crypto.util.extended_date object
        """

        if year is None:
            year = self.year
        if month is None:
            month = self.month
        if day is None:
            day = self.day

        if year > 0:
            cls = date
        else:
            cls = extended_date

        return cls(
            year,
            month,
            day
        ) 
Example 34
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def _comparison_error(self, other):
        raise TypeError(unwrap(
            '''
            An asn1crypto.util.extended_date object can only be compared to
            an asn1crypto.util.extended_date or datetime.date object, not %s
            ''',
            type_name(other)
        )) 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def date(self):
        """
        :return:
            An asn1crypto.util.extended_date of the date
        """

        return extended_date(self.year, self.month, self.day) 
Example 36
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 5 votes vote down vote up
def __deserialize(self, data, klass):
        """
        Deserializes dict, list, str into an object.

        :param data: dict, list or str.
        :param klass: class literal, or string of class name.

        :return: object.
        """
        if data is None:
            return None

        if type(klass) == str:
            if klass.startswith('list['):
                sub_kls = re.match('list\[(.*)\]', klass).group(1)
                return [self.__deserialize(sub_data, sub_kls)
                        for sub_data in data]

            if klass.startswith('dict('):
                sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2)
                return {k: self.__deserialize(v, sub_kls)
                        for k, v in iteritems(data)}

            # convert str to class
            if klass in self.NATIVE_TYPES_MAPPING:
                klass = self.NATIVE_TYPES_MAPPING[klass]
            else:
                klass = getattr(models, klass)

        if klass in self.PRIMITIVE_TYPES:
            return self.__deserialize_primitive(data, klass)
        elif klass == object:
            return self.__deserialize_object(data)
        elif klass == date:
            return self.__deserialize_date(data)
        elif klass == datetime:
            return self.__deserialize_datatime(data)
        else:
            return self.__deserialize_model(data, klass) 
Example 37
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 5 votes vote down vote up
def snapshot_retain_weekly(self, snapname, retention):
        try:
            dts = re.match(r'\w+-(\d+)', snapname).groups()[0]
        except AttributeError:
            return True  # Keep
        datetimestamp = datetime.strptime(dts, '%Y%m%d%H%M')
        snapdate = datetime.date(datetimestamp)
        today_a_week_ago = datetime.date(
            datetime.now() - relativedelta(weeks=retention+1))
        return snapdate >= today_a_week_ago 
Example 38
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 5 votes vote down vote up
def snapshot_retain_monthly(self, snapname, retention):
        try:
            dts = re.match(r'\w+-(\d+)', snapname).groups()[0]
        except AttributeError:
            return True  # Keep

        datetimestamp = datetime.strptime(dts, '%Y%m%d%H%M')
        snapdate = datetime.date(datetimestamp)
        today_a_month_ago = datetime.date(
            datetime.now() - relativedelta(months=retention+1))
        return snapdate >= today_a_month_ago 
Example 39
Project: planb   Author: ossobv   File: zfs.py    GNU General Public License v3.0 5 votes vote down vote up
def snapshot_retain_yearly(self, snapname, retention):
        try:
            dts = re.match(r'\w+-(\d+)', snapname).groups()[0]
        except AttributeError:
            return True  # Keep
        datetimestamp = datetime.strptime(dts, '%Y%m%d%H%M')
        snapdate = datetime.date(datetimestamp)
        today_a_year_ago = datetime.date(
            datetime.now() - relativedelta(years=retention+1))
        return snapdate >= today_a_year_ago 
Example 40
Project: SouthwestBot   Author: TAAPArthur   File: southwestObjects.py    MIT License 5 votes vote down vote up
def getDate(self):
        return datetime.date(self.departureTime) 
Example 41
Project: SouthwestBot   Author: TAAPArthur   File: southwestObjects.py    MIT License 5 votes vote down vote up
def getDates(self):
        dateRange = list(range(-self.startDate, self.endDate))
        dateRange.sort(key=lambda x: abs(x))
        date = self.getDate()
        return list(map(lambda x: date-timedelta(x), dateRange)) 
Example 42
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_start_date(self):
        """Returns the start date of current position. Used in Admin Interface. See PersonAdmin in admin.py"""
        latest_position = self.get_latest_position()
        if latest_position is not None:
            return latest_position.start_date
        else:
            return None 
Example 43
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_end_date(self):
        """Returns the end date of current position. Used in Admin Interface. See PersonAdmin in admin.py"""
        latest_position = self.get_latest_position()
        if latest_position is not None:
            return latest_position.end_date
        else:
            return None 
Example 44
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_projects(self):
        """
        Gets a set of all the projects this person is involved in ordered by most recent start date first
        :return: a set of all the projects this person is involved in ordered by most recent start date first
        """
        project_roles = self.project_role_set.order_by('-start_date')

        # For more on this style of list iteration (called list comprehension)
        # See: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
        #      https://www.python.org/dev/peps/pep-0202/
        projects = set([project_role.project for project_role in project_roles])
        return projects 
Example 45
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_time_in_this_position(self):
        if self.end_date is not None and self.start_date is not None:
            return self.end_date - self.start_date
        elif self.end_date is None and self.start_date is not None:
            return date.today() - self.start_date
        else:
            return None

    # Returns the start and end dates as strings 
Example 46
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def is_current_collaborator(self):
        return self.is_collaborator() and \
               (self.start_date is not None and self.start_date <= date.today() and \
                self.end_date is None or (self.end_date is not None and self.end_date >= date.today()))

    # Returns true if collaborator is a past collaborator (used to differentiate between future collaborators) 
Example 47
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def is_past_collaborator(self):
        return self.is_collaborator() and \
               self.start_date < date.today() and \
               self.end_date != None and self.end_date < date.today()

    # Returns true if member is an alumni member (used to differentiate between future members) 
Example 48
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def is_alumni_member(self):
        return self.is_member() and \
               self.start_date < date.today() and \
               self.end_date != None and self.end_date < date.today()

    # Automatically called by Django when saving data to validate the data 
Example 49
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def clean(self):
        if self.end_date is not None and self.start_date > self.end_date:
            raise ValidationError('The start date must be before the end date') 
Example 50
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_most_recent_publication(self):
        """Returns the most recent publication for project"""
        if self.publication_set.exists():
            return self.publication_set.order_by('-date')[0]
        else:
            return None 
Example 51
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_most_recent_artifact_date(self):
        """
        Returns the most recent artifact date (if one exists); otherwise None
        :return: the most recent artifact date (if one exists); otherwise None
        """
        most_recent_artifact_tuple = self.get_most_recent_artifact()
        if most_recent_artifact_tuple is not None:
            return most_recent_artifact_tuple[0]
        else:
            return None 
Example 52
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def get_end_date_short(self):
        # if this project role has no end date, check to see if the project itself has ended
        # and use the end date for that instead
        # See: https://github.com/jonfroehlich/makeabilitylabwebsite/issues/836
        if self.end_date is None and self.project.has_ended():
            return self.project.end_date.strftime('%b %Y')
        elif self.end_date is None:
            return "Present" # project is still active and role has no end date
        else:
            return self.end_date.strftime('%b %Y') 
Example 53
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def is_active(self):
        return self.start_date is not None and self.start_date <= date.today() and \
               (self.end_date is None or self.end_date >= date.today())

    # This function is used to differentiate between past and future roles 
Example 54
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def is_past(self):
        return self.start_date is not None and self.start_date < date.today() and \
               (self.end_date is not None and self.end_date < date.today()) 
Example 55
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def __str__(self):
        return "{}, {}, {}".format(self.title, self.get_video_host_str(), self.date)

#TODO: figure out why we need this and then move it somewhere 
Example 56
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def __str__(self):
        return "{}, {}, {} {}".format(self.get_person().get_full_name(), self.title, self.forum_name, self.date)

#@receiver(post_save, sender=Talk) 
Example 57
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def __str__(self):
        return "{}, {}, {}".format(self.get_person().get_full_name(), self.title, self.date) 
Example 58
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def update_file_name_publication(sender, instance, action, reverse, **kwargs):
    # Reverse: Indicates which side of the relation is updated (i.e., if it is the forward or reverse relation that is being modified)
    # Action: A string indicating the type of update that is done on the relation.
    # post_add: Sent after one or more objects are added to the relation
    if action == 'post_add' and not reverse:
        initial_path = instance.pdf_file.path
        person = instance.get_person()
        name = person.last_name
        year = instance.date.year
        title = ''.join(x for x in instance.title.title() if not x.isspace())
        title = ''.join(e for e in title if e.isalnum())

        # Get the publication venue but remove proceedings from it (if it exists)
        forum = instance.book_title_short.lower()
        if "proceedings of" in forum.lower():
            forum = forum.replace('proceedings of', '')

        forum = forum.strip().upper()
        forum = ''.join(x for x in forum if not x.isspace())

        if not forum[-1].isdigit():
            forum = forum + str(year)

        #change the path of the pdf file to point to the new file name
        instance.pdf_file.name = os.path.join('publications', name + '_' + title + '_' + forum + '.pdf')
        new_path = os.path.join(settings.MEDIA_ROOT, instance.pdf_file.name)
        os.rename(initial_path, new_path)
        instance.save() 
Example 59
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 5 votes vote down vote up
def short_date(self):
        month = self.date.strftime('%b')
        day = self.date.strftime('%d')
        year = self.date.strftime('%Y')
        return month + " " + day + ", " + year 
Example 60
Project: Aegis   Author: jlillywh   File: time_series.py    GNU General Public License v3.0 5 votes vote down vote up
def start_date(self):
        """ The calendar time of the *first* datetime or etime of the time series.
        
        Returns:
            datetime.date: the return value
        """
        return self.df.index.min() 
Example 61
Project: Aegis   Author: jlillywh   File: time_series.py    GNU General Public License v3.0 5 votes vote down vote up
def end_date(self):
        """ The calendar time of the *last* datetime or etime of the time series.
        
        Returns:
            datetime.date: the return value
        """
        return self.df.index.max() 
Example 62
Project: year2018   Author: baijiangliang   File: repository.py    MIT License 5 votes vote down vote up
def get_busiest_day(self) -> Tuple[datetime.date, Dict[str, Any]]:
        """ Get the day which has max commit weight. """
        commits = self.get_commit_stat_by_day()
        busiest_day = max(commits.keys(), key=lambda x: commits[x]['weight'])
        return busiest_day, commits[busiest_day] 
Example 63
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def rollback(self, dt):
        """
        Roll provided date backward to next offset only if not on offset.

        Returns
        -------
        TimeStamp
            Rolled timestamp if not on offset, otherwise unchanged timestamp.
        """
        dt = as_timestamp(dt)
        if not self.onOffset(dt):
            dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds)
        return dt 
Example 64
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def rollforward(self, dt):
        """
        Roll provided date forward to next offset only if not on offset.

        Returns
        -------
        TimeStamp
            Rolled timestamp if not on offset, otherwise unchanged timestamp.
        """
        dt = as_timestamp(dt)
        if not self.onOffset(dt):
            dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
        return dt 
Example 65
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        # XXX, see #1395
        if type(self) == DateOffset or isinstance(self, Tick):
            return True

        # Default (slow) method for determining if some date is a member of the
        # date range generated by this offset. Subclasses may have this
        # re-implemented in a nicer way.
        a = dt
        b = (dt + self) - self
        return a == b

    # way to get around weirdness with rule_code 
Example 66
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def rollforward(self, dt):
        """
        Roll provided date forward to next offset only if not on offset.
        """
        if not self.onOffset(dt):
            if self.n >= 0:
                return self._next_opening_time(dt)
            else:
                return self._prev_opening_time(dt)
        return dt 
Example 67
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def apply(self, other):
        if self.n <= 0:
            roll = "forward"
        else:
            roll = "backward"

        if isinstance(other, datetime):
            date_in = other
            np_dt = np.datetime64(date_in.date())

            np_incr_dt = np.busday_offset(
                np_dt, self.n, roll=roll, busdaycal=self.calendar
            )

            dt_date = np_incr_dt.astype(datetime)
            result = datetime.combine(dt_date, date_in.time())

            if self.offset:
                result = result + self.offset
            return result

        elif isinstance(other, (timedelta, Tick)):
            return BDay(self.n, offset=self.offset + other, normalize=self.normalize)
        else:
            raise ApplyTypeError(
                "Only know how to combine trading day with "
                "datetime, datetime64 or timedelta."
            ) 
Example 68
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def apply_index(self, i):
        # determine how many days away from the 1st of the month we are
        dti = i
        days_from_start = i.to_perioddelta("M").asi8
        delta = Timedelta(days=self.day_of_month - 1).value

        # get boolean array for each element before the day_of_month
        before_day_of_month = days_from_start < delta

        # get boolean array for each element after the day_of_month
        after_day_of_month = days_from_start > delta

        # determine the correct n for each date in i
        roll = self._get_roll(i, before_day_of_month, after_day_of_month)

        # isolate the time since it will be striped away one the next line
        time = i.to_perioddelta("D")

        # apply the correct number of months

        # integer-array addition on PeriodIndex is deprecated,
        #  so we use _addsub_int_array directly
        asper = i.to_period("M")
        if not isinstance(asper._data, np.ndarray):
            # unwrap PeriodIndex --> PeriodArray
            asper = asper._data

        shifted = asper._addsub_int_array(roll // 2, operator.add)
        i = type(dti)(shifted.to_timestamp())

        # apply the correct day
        i = self._apply_index_days(i, roll)

        return i + time 
Example 69
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def _get_roll(self, i, before_day_of_month, after_day_of_month):
        """
        Return an array with the correct n for each date in i.

        The roll array is based on the fact that i gets rolled back to
        the first day of the month.
        """
        raise AbstractMethodError(self) 
Example 70
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def _apply_index_days(self, i, roll):
        """
        Apply the correct day for each date in i.
        """
        raise AbstractMethodError(self) 
Example 71
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def apply(self, other):
        current_easter = easter(other.year)
        current_easter = datetime(
            current_easter.year, current_easter.month, current_easter.day
        )
        current_easter = conversion.localize_pydatetime(current_easter, other.tzinfo)

        n = self.n
        if n >= 0 and other < current_easter:
            n -= 1
        elif n < 0 and other > current_easter:
            n += 1
        # TODO: Why does this handle the 0 case the opposite of others?

        # NOTE: easter returns a datetime.date so we have to convert to type of
        # other
        new = easter(other.year + n)
        new = datetime(
            new.year,
            new.month,
            new.day,
            other.hour,
            other.minute,
            other.second,
            other.microsecond,
        )
        return new 
Example 72
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 5 votes vote down vote up
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False
        return date(dt.year, dt.month, dt.day) == easter(dt.year)


# ---------------------------------------------------------------------
# Ticks 
Example 73
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: test_tools.py    MIT License 5 votes vote down vote up
def test_to_datetime_parse_timezone_malformed(self, offset):
        fmt = "%Y-%m-%d %H:%M:%S %z"
        date = "2010-01-01 12:00:00 " + offset
        with pytest.raises(ValueError):
            pd.to_datetime([date], format=fmt) 
Example 74
Project: reroils-data-legacy   Author: rero   File: api.py    GNU General Public License v2.0 4 votes vote down vote up
def find_by_holding(cls, **kwargs):
        """Find item versions based on their holdings information.

        Every given kwarg will be queried as a key-value pair in the items
        holding.

        :returns: List[(UUID, version_id)] with `version_id` as used by
                  `RecordMetadata.version_id`.
        """
        def _get_filter_clause(obj, key, value):
            val = obj[key].astext
            CASTS = {
                bool: lambda x: cast(x, BOOLEAN),
                int: lambda x: cast(x, INTEGER),
                datetime.date: lambda x: cast(x, DATE),
            }
            if (not isinstance(value, six.string_types) and
                    isinstance(value, collections.Sequence)):
                if len(value) == 2:
                    return CASTS[type(value[0])](val).between(*value)
                raise ValueError('Too few/many values for a range query. '
                                 'Range query requires two values.')
            return CASTS.get(type(value), lambda x: x)(val) == value

        RecordMetadataVersion = version_class(RecordMetadata)

        data = type_coerce(RecordMetadataVersion.json, JSONB)
        path = ('_circulation', 'holdings')

        subquery = db.session.query(
            RecordMetadataVersion.id.label('id'),
            RecordMetadataVersion.version_id.label('version_id'),
            func.json_array_elements(data[path]).label('obj')
        ).subquery()

        obj = type_coerce(subquery.c.obj, JSONB)

        query = db.session.query(
            RecordMetadataVersion.id,
            RecordMetadataVersion.version_id
        ).filter(
            RecordMetadataVersion.id == subquery.c.id,
            RecordMetadataVersion.version_id == subquery.c.version_id,
            *(_get_filter_clause(obj, k, v) for k, v in kwargs.items())
        )

        for result in query:
            yield result 
Example 75
Project: esp-sdk-python   Author: EvidentSecurity   File: api_client.py    MIT License 4 votes vote down vote up
def sanitize_for_serialization(self, obj):
        """
        Builds a JSON POST object.

        If obj is None, return None.
        If obj is str, int, long, float, bool, return directly.
        If obj is datetime.datetime, datetime.date
            convert to string in iso8601 format.
        If obj is list, sanitize each element in the list.
        If obj is dict, return the dict.
        If obj is swagger model, return the properties dict.

        :param obj: The data to serialize.
        :return: The serialized form of data.
        """
        if obj is None:
            return None
        elif isinstance(obj, self.PRIMITIVE_TYPES):
            return obj
        elif isinstance(obj, list):
            return [self.sanitize_for_serialization(sub_obj)
                    for sub_obj in obj]
        elif isinstance(obj, tuple):
            return tuple(self.sanitize_for_serialization(sub_obj)
                         for sub_obj in obj)
        elif isinstance(obj, (datetime, date)):
            return obj.isoformat()

        if isinstance(obj, dict):
            obj_dict = obj
        else:
            # Convert model obj to dict except
            # attributes `swagger_types`, `attribute_map`
            # and attributes which value is not None.
            # Convert attribute name to json key in
            # model definition for request.
            obj_dict = {obj.attribute_map[attr]: getattr(obj, attr)
                        for attr, _ in iteritems(obj.swagger_types)
                        if getattr(obj, attr) is not None}

        return {key: self.sanitize_for_serialization(val)
                for key, val in iteritems(obj_dict)} 
Example 76
Project: SouthwestBot   Author: TAAPArthur   File: southwestScraper.py    MIT License 4 votes vote down vote up
def getRecentFlights(self, savedUpComingFlights):

        tripLinks = []
        flights = []
        i = 0
        while True:
            tripElements = self.driver.find_elements_by_class_name("upcoming-trip-details-list-link")
            for tripElement in tripElements:
                tripLinks.append(tripElement.get_attribute("href"))
            nextButton = self.driver.find_element_by_class_name(
                "js-functional-bar-upcoming").find_element_by_class_name("js-right-arrow")
            if nextButton.get_attribute("disabled"):
                break
            else:
                self.waitForElementToToBeClickableByClass("js-right-arrow")
                nextButton.click()
                time.sleep(1)
            i += 1
            if i == 60:
                self.saveScreenshot("getRecentFlights.png")
                self.output("could not get recent flights")
                return[]
        for link in tripLinks:
            self.driver.get(link)
            self.output(link)

            confirmationNumber = self.waitForElementToHaveTextByClass("upcoming-details--confirmation-number")
            assert confirmationNumber != ""
            title = self.driver.find_element_by_class_name("upcoming-details--title").text
            rawDate = self.driver.find_elements_by_class_name("flight-details--date")

            firstRow = self.driver.find_elements_by_class_name("flight-details--first-row")
            lastRow = self.driver.find_elements_by_class_name("flight-details--row-last-child")
            assert len(rawDate) == len(firstRow)
            for i in range(len(rawDate)):
                date = rawDate[i].text.strip()
                assert date != ""

                startTime = firstRow[i].find_element_by_class_name("flight-details--trip-time").text.strip()
                endTime = lastRow[i].find_element_by_class_name("flight-details--trip-time").text.strip()
                origin = firstRow[i].find_element_by_class_name("flight-details--city").text
                dest = lastRow[i].find_element_by_class_name("flight-details--city").text
                departureTime = datetime.strptime(date+" "+startTime, "%m/%d/%y %I:%M%p")
                arrivalTime = datetime.strptime(date+" "+endTime, "%m/%d/%y %I:%M%p")
                flightNumber = int(firstRow[i].find_element_by_class_name("flight-details--flight-number").text)
                flight = Flight(title=title, confirmationNumber=confirmationNumber, departureTime=departureTime, arrivalTime=arrivalTime,
                                origin=origin, dest=dest, flightNumber=flightNumber, startDate=self.user.defaultDeltaStart, endDate=self.user.defaultDeltaEnd)

                if flight in savedUpComingFlights:
                    flight.copyMetadata(savedUpComingFlights[flight], self.user)

                flights.append(flight)

        return flights 
Example 77
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 4 votes vote down vote up
def get_projects_sorted_by_contrib(self, filter_out_projs_with_zero_pubs=True):
        """Returns a set of all projects this person is involved in ordered by number of pubs"""
        map_project_name_to_tuple = dict() # tuple is (count, most_recent_pub_date, project)
        #publications = self.publication_set.order_by('-date')

        # Go through all the projects by this person and track how much
        # they've contributed to each one (via publication)
        #print("******{}*******".format(self.get_full_name()))
        for pub in self.publication_set.all():
            for proj in pub.projects.all():
                #print("pub", pub, "proj", proj)
                if proj.name not in map_project_name_to_tuple:
                    most_recent_date = proj.start_date
                    if most_recent_date is None:
                        most_recent_date = pub.date
                    if most_recent_date is None:
                        most_recent_date = datetime.date(2012, 1, 1) # when the lab was founded

                    map_project_name_to_tuple[proj.name] = (0, most_recent_date, proj)

                tuple_cnt_proj = map_project_name_to_tuple[proj.name]
                most_recent_date = tuple_cnt_proj[1]
                if pub.date is not None and pub.date > most_recent_date:
                    most_recent_date = pub.date

                map_project_name_to_tuple[proj.name] = (tuple_cnt_proj[0] + 1, # pub cnt
                                                        most_recent_date,      # most recent pub date
                                                        tuple_cnt_proj[2])     # project

        list_tuples = list([tuple_cnt_proj for tuple_cnt_proj in map_project_name_to_tuple.values()])
        list_tuples_sorted = sorted(list_tuples, key=lambda t: (t[0], t[1]), reverse=True)

        #print("list_tuples_sorted", list_tuples_sorted)

        ordered_projects = []
        if len(list_tuples_sorted) > 0:
            list_cnts, list_dates, ordered_projects = zip(*list_tuples_sorted)

        if len(ordered_projects) <= 0 and not filter_out_projs_with_zero_pubs:
            # if a person hasn't published but is still on projects
            # default to this
            ordered_projects = self.get_projects()

        return ordered_projects 
Example 78
Project: makeabilitylabwebsite   Author: jonfroehlich   File: models.py    MIT License 4 votes vote down vote up
def update_file_name_talks(sender, instance, action, reverse, **kwargs):
    #Reverse: Indicates which side of the relation is updated (i.e., if it is the forward or reverse relation that is being modified)
    #Action: A string indicating the type of update that is done on the relation.
    #post_add: Sent after one or more objects are added to the relation

    # from: https://docs.djangoproject.com/en/2.1/ref/signals/
    if action == 'post_add' and not reverse:
        initial_path = instance.pdf_file.path
        person = instance.get_person()
        name = person.last_name
        year = instance.date.year
        title = ''.join(x for x in instance.title.title() if not x.isspace())
        title = ''.join(e for e in title if e.isalnum())

        #change the pdf_file path to point to the renamed file
        instance.pdf_file.name = os.path.join('talks', name + '_' + title + '_' + str(year) + '.pdf')
        new_path = os.path.join(settings.MEDIA_ROOT, instance.pdf_file.name)
        os.rename(initial_path, new_path)
        instance.save()

        # old_pdf_filename_with_path = instance.pdf_file.path
        # new_pdf_filename = get_formatted_filename(instance.get_person(), instance.title, instance.date.year, '.pdf')
        #
        # old_raw_filename_with_path = instance.raw_file.path
        # raw_ext = os.path.splitext(instance.raw_file.path)[1]
        # new_raw_filename = get_formatted_filename(instance.get_person(), instance.title, instance.date.year, raw_ext)


# def get_formatted_filename(person, title_str, year, ext):
#     initial_path = instance.pdf_file.path
#     person = instance.get_person()
#     name = person.last_name
#     year = instance.date.year
#     title = instance.title.title()
#     title = ''.join(x for x in title if not x.isspace())
#     title = ''.join(e for e in title if e.isalnum())
#
#     # change the pdf_file path to point to the renamed file
#     instance.pdf_file.name = os.path.join(dir_name, name + '_' + title + '_' + str(year) + '.pdf')
#     new_path = os.path.join(settings.MEDIA_ROOT, instance.pdf_file.name)
#     os.rename(initial_path, new_path)
#     instance.save() 
Example 79
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 4 votes vote down vote up
def apply_wraps(func):
    @functools.wraps(func)
    def wrapper(self, other):
        if other is NaT:
            return NaT
        elif isinstance(other, (timedelta, Tick, DateOffset)):
            # timedelta path
            return func(self, other)
        elif isinstance(other, (np.datetime64, datetime, date)):
            other = as_timestamp(other)

        tz = getattr(other, "tzinfo", None)
        nano = getattr(other, "nanosecond", 0)

        try:
            if self._adjust_dst and isinstance(other, Timestamp):
                other = other.tz_localize(None)

            result = func(self, other)

            if self._adjust_dst:
                result = conversion.localize_pydatetime(result, tz)

            result = Timestamp(result)
            if self.normalize:
                result = result.normalize()

            # nanosecond may be deleted depending on offset process
            if not self.normalize and nano != 0:
                if not isinstance(self, Nano) and result.nanosecond != nano:
                    if result.tz is not None:
                        # convert to UTC
                        value = conversion.tz_convert_single(
                            result.value, timezones.UTC, result.tz
                        )
                    else:
                        value = result.value
                    result = Timestamp(value + nano)

            if tz is not None and result.tzinfo is None:
                result = conversion.localize_pydatetime(result, tz)

        except OutOfBoundsDatetime:
            result = func(self, as_datetime(other))

            if self.normalize:
                # normalize_date returns normal datetime
                result = normalize_date(result)

            if tz is not None and result.tzinfo is None:
                result = conversion.localize_pydatetime(result, tz)

            result = Timestamp(result)

        return result

    return wrapper


# ---------------------------------------------------------------------
# DateOffset 
Example 80
Project: FX-RER-Value-Extraction   Author: tsKenneth   File: offsets.py    MIT License 4 votes vote down vote up
def _rollback_to_year(self, other):
        """
        Roll `other` back to the most recent date that was on a fiscal year
        end.

        Return the date of that year-end, the number of full quarters
        elapsed between that year-end and other, and the remaining Timedelta
        since the most recent quarter-end.

        Parameters
        ----------
        other : datetime or Timestamp

        Returns
        -------
        tuple of
        prev_year_end : Timestamp giving most recent fiscal year end
        num_qtrs : int
        tdelta : Timedelta
        """
        num_qtrs = 0

        norm = Timestamp(other).tz_localize(None)
        start = self._offset.rollback(norm)
        # Note: start <= norm and self._offset.onOffset(start)

        if start < norm:
            # roll adjustment
            qtr_lens = self.get_weeks(norm)

            # check thet qtr_lens is consistent with self._offset addition
            end = liboffsets.shift_day(start, days=7 * sum(qtr_lens))
            assert self._offset.onOffset(end), (start, end, qtr_lens)

            tdelta = norm - start
            for qlen in qtr_lens:
                if qlen * 7 <= tdelta.days:
                    num_qtrs += 1
                    tdelta -= Timedelta(days=qlen * 7)
                else:
                    break
        else:
            tdelta = Timedelta(0)

        # Note: we always have tdelta.value >= 0
        return start, num_qtrs, tdelta