Python datetime.date() Examples

The following are code examples for showing how to use 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: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 6 votes vote down vote up
def _set_date_tuple(self, mediafile, year, month=None, day=None):
        """Set the value of the field given a year, month, and day
        number. Each number can be an integer or None to indicate an
        unset component.
        """
        if year is None:
            self.__delete__(mediafile)
            return

        date = [u'{0:04d}'.format(int(year))]
        if month:
            date.append(u'{0:02d}'.format(int(month)))
        if month and day:
            date.append(u'{0:02d}'.format(int(day)))
        date = map(six.text_type, date)
        super(DateField, self).__set__(mediafile, u'-'.join(date))

        if hasattr(self, '_year_field'):
            self._year_field.__set__(mediafile, year) 
Example 3
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 6 votes vote down vote up
def test_delete_partial_date(self):
        mediafile = self._mediafile_fixture('empty')

        mediafile.date = datetime.date(2001, 12, 3)
        mediafile.save()
        mediafile = MediaFile(mediafile.path)
        self.assertIsNotNone(mediafile.date)
        self.assertIsNotNone(mediafile.year)
        self.assertIsNotNone(mediafile.month)
        self.assertIsNotNone(mediafile.day)

        delattr(mediafile, 'month')
        mediafile.save()
        mediafile = MediaFile(mediafile.path)
        self.assertIsNotNone(mediafile.date)
        self.assertIsNotNone(mediafile.year)
        self.assertIsNone(mediafile.month)
        self.assertIsNone(mediafile.day) 
Example 4
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 6 votes vote down vote up
def datetime_or_default(date, default):
    """Return a datetime-like object or a default.

    Parameters
    ----------
    date : `None` or datetime-like object or str
    default : The value to return if `date` is `None`

    Returns
    -------
    `default` if `date` is `None`, otherwise returns the result of
    `utils.times.ensure_datetime(date)`

    """
    if date is None:
        return default
    else:
        return ensure_datetime(date) 
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: 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 7
Project: cplot   Author: sunchaoatmo   File: cstoolkit.py    GNU General Public License v3.0 6 votes vote down vote up
def eritimeselection(start_year,start_month,start_day,
                     end_year,end_month,end_day,
                     eri_time_origin,time_eri):
  from matplotlib import dates
  from datetime import date,timedelta
  time_start=date(start_year,start_month,start_day)
  time_end=date(end_year,end_month,end_day)
  start_rel_date=dates.date2num(time_start)-dates.date2num(eri_time_origin)
  end_rel_date=dates.date2num(time_end)-dates.date2num(eri_time_origin)
  start_rel_hour=int(start_rel_date*24)
  end_rel_hour=int(end_rel_date*24)
  eri_select_b=list(time_eri).index(12+start_rel_hour)
  eri_select_e=list(time_eri).index(12+  end_rel_hour)
  eri_start=eri_time_origin+timedelta(hours=int(time_eri[eri_select_b]))
  eri_end=eri_time_origin+timedelta(hours=int(time_eri[eri_select_e]))
  print("Eri data starting from %s till %s"% (eri_start.strftime('%Y%m%d'),eri_end.strftime('%Y%m%d')))
  return (eri_select_b,eri_select_e) 
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: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 5 votes vote down vote up
def doekoe_neo(relative_to=datetime.datetime.today()):
    '''
    Bereken wanneer de uitbetalingen in RULES gebeuren.

    Vraag uw specialist en/of gebruik uw ogen om de inhoud van RULES te achterhalen.
    '''
    result = ''

    relative_to.replace(hour=0, minute=0, second=0, microsecond=0)

    LOGGER.debug('relative_to %s', relative_to)
    for item in next_occurrences(relative_to):
        LOGGER.debug('%s %s', item[0], item[1])
        if item[1] == relative_to.date():
            result += '{} is vandaag! ({})\n'.format(
                item[0].name, item[1])
        else:
            delta = relativedelta(item[1], relative_to.date())
            LOGGER.debug('Delta: %s (%s)', delta, delta.days)
            numdays = delta.days
            word = 'dag' if numdays == 1 else 'dagen'
            result += '{} komt over {} {}. ({})\n'.format(
                item[0].name, numdays, word, item[1])

    result += '\n\nAan deze informatie kunnen geen rechten worden ontleend.'
    return result 
Example 10
Project: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 5 votes vote down vote up
def next_occurrences(relative_to=datetime.datetime.today()):
    '''
    Calculate when the rules in RULES will next fire.
    Returns a list of (Rule, datetime.date) tuples.
    '''
    result = []
    for rule in RULES:
        yesterday = relative_to - datetime.timedelta(days=1)
        naive_next = rule.rule.after(yesterday)
        actual_next = rule.relocator(naive_next)
        result.append((rule, actual_next))

    return result 
Example 11
Project: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 5 votes vote down vote up
def which_today(relative_to=datetime.datetime.today()):
    ''' List all events which should happen on the same date as relative_to. '''
    todays_events = [x[0].name for x in next_occurrences(relative_to)
                     if x[1] == date.today()]
    return todays_events 
Example 12
Project: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 5 votes vote down vote up
def first_weekday_after(arg):
    '''
    Find the first weekday on or after the given date.

    If the argument is a Saturday or Sunday, the Monday after is returned.
    '''
    if hasattr(arg, 'date'):
        arg = arg.date()
    if arg.weekday() < 5:
        return arg
    return arg + relativedelta(days=7 - arg.weekday()) 
Example 13
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 5 votes vote down vote up
def __init__(self, *date_styles, **kwargs):
        """``date_styles`` is a list of ``StorageStyle``s to store and
        retrieve the whole date from. The ``year`` option is an
        additional list of fallback styles for the year. The year is
        always set on this style, but is only retrieved if the main
        storage styles do not return a value.
        """
        super(DateField, self).__init__(*date_styles)
        year_style = kwargs.get('year', None)
        if year_style:
            self._year_field = MediaField(*year_style) 
Example 14
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 5 votes vote down vote up
def __get__(self, mediafile, owner=None):
        year, month, day = self._get_date_tuple(mediafile)
        if not year:
            return None
        try:
            return datetime.date(
                year,
                month or 1,
                day or 1
            )
        except ValueError:  # Out of range values.
            return None 
Example 15
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 5 votes vote down vote up
def __set__(self, mediafile, date):
        if date is None:
            self._set_date_tuple(mediafile, None, None, None)
        else:
            self._set_date_tuple(mediafile, date.year, date.month, date.day) 
Example 16
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 5 votes vote down vote up
def _get_date_tuple(self, mediafile):
        """Get a 3-item sequence representing the date consisting of a
        year, month, and day number. Each number is either an integer or
        None.
        """
        # Get the underlying data and split on hyphens and slashes.
        datestring = super(DateField, self).__get__(mediafile, None)
        if isinstance(datestring, six.string_types):
            datestring = re.sub(r'[Tt ].*$', '', six.text_type(datestring))
            items = re.split('[-/]', six.text_type(datestring))
        else:
            items = []

        # Ensure that we have exactly 3 components, possibly by
        # truncating or padding.
        items = items[:3]
        if len(items) < 3:
            items += [None] * (3 - len(items))

        # Use year field if year is missing.
        if not items[0] and hasattr(self, '_year_field'):
            items[0] = self._year_field.__get__(mediafile)

        # Convert each component to an integer if possible.
        items_ = []
        for item in items:
            try:
                items_.append(int(item))
            except (TypeError, ValueError):
                items_.append(None)
        return items_ 
Example 17
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_write_incomplete_date_components(self):
        mediafile = self._mediafile_fixture('empty')
        mediafile.year = 2001
        mediafile.month = None
        mediafile.day = 2
        mediafile.save()

        mediafile = MediaFile(mediafile.path)
        self.assertEqual(mediafile.year, 2001)
        self.assertIsNone(mediafile.month)
        self.assertIsNone(mediafile.day)
        self.assertEqual(mediafile.date, datetime.date(2001, 1, 1)) 
Example 18
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_write_dates(self):
        mediafile = self._mediafile_fixture('full')
        mediafile.date = datetime.date(2001, 1, 2)
        mediafile.original_date = datetime.date(1999, 12, 30)
        mediafile.save()

        mediafile = MediaFile(mediafile.path)
        self.assertEqual(mediafile.year, 2001)
        self.assertEqual(mediafile.month, 1)
        self.assertEqual(mediafile.day, 2)
        self.assertEqual(mediafile.date, datetime.date(2001, 1, 2))
        self.assertEqual(mediafile.original_year, 1999)
        self.assertEqual(mediafile.original_month, 12)
        self.assertEqual(mediafile.original_day, 30)
        self.assertEqual(mediafile.original_date, datetime.date(1999, 12, 30)) 
Example 19
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_unparseable_date(self):
        """The `unparseable.*` fixture should not crash but should return None
        for all parts of the release date.
        """
        mediafile = self._mediafile_fixture('unparseable')

        self.assertIsNone(mediafile.date)
        self.assertIsNone(mediafile.year)
        self.assertIsNone(mediafile.month)
        self.assertIsNone(mediafile.day) 
Example 20
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_delete_year(self):
        mediafile = self._mediafile_fixture('full')

        self.assertIsNotNone(mediafile.date)
        self.assertIsNotNone(mediafile.year)

        delattr(mediafile, 'year')
        mediafile.save()
        mediafile = MediaFile(mediafile.path)
        self.assertIsNone(mediafile.date)
        self.assertIsNone(mediafile.year) 
Example 21
Project: phrydy   Author: Josef-Friedrich   File: test_mediafile.py    MIT License 5 votes vote down vote up
def test_read_date_from_year_tag(self):
        mediafile = self._mediafile_fixture('year')
        self.assertEqual(mediafile.year, 2000)
        self.assertEqual(mediafile.date, datetime.date(2000, 1, 1)) 
Example 22
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def register_adapters_and_converters():
    def adapt_date(val):
        return val.isoformat()

    def adapt_datetime(val):
        return val.isoformat(" ")

    def convert_date(val):
        return datetime.date(*map(int, val.split("-")))

    def convert_timestamp(val):
        datepart, timepart = val.split(" ")
        year, month, day = map(int, datepart.split("-"))
        timepart_full = timepart.split(".")
        hours, minutes, seconds = map(int, timepart_full[0].split(":"))
        if len(timepart_full) == 2:
            microseconds = int('{:0<6.6}'.format(timepart_full[1].decode()))
        else:
            microseconds = 0

        val = datetime.datetime(year, month, day, hours, minutes, seconds, microseconds)
        return val


    register_adapter(datetime.date, adapt_date)
    register_adapter(datetime.datetime, adapt_datetime)
    register_converter("date", convert_date)
    register_converter("timestamp", convert_timestamp) 
Example 23
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_week_of_year_and_day_of_week_calculation(self):
        # Should be able to infer date if given year, week of year (%U or %W)
        # and day of the week
        def test_helper(ymd_tuple, test_reason):
            for directive in ('W', 'U'):
                format_string = "%%Y %%%s %%w" % directive
                dt_date = datetime_date(*ymd_tuple)
                strp_input = dt_date.strftime(format_string)
                strp_output = _strptime._strptime_time(strp_input, format_string)
                self.assertTrue(strp_output[:3] == ymd_tuple,
                        "%s(%s) test failed w/ '%s': %s != %s (%s != %s)" %
                            (test_reason, directive, strp_input,
                                strp_output[:3], ymd_tuple,
                                strp_output[7], dt_date.timetuple()[7]))
        test_helper((1901, 1, 3), "week 0")
        test_helper((1901, 1, 8), "common case")
        test_helper((1901, 1, 13), "day on Sunday")
        test_helper((1901, 1, 14), "day on Monday")
        test_helper((1905, 1, 1), "Jan 1 on Sunday")
        test_helper((1906, 1, 1), "Jan 1 on Monday")
        test_helper((1906, 1, 7), "first Sunday in a year starting on Monday")
        test_helper((1905, 12, 31), "Dec 31 on Sunday")
        test_helper((1906, 12, 31), "Dec 31 on Monday")
        test_helper((2008, 12, 29), "Monday in the last week of the year")
        test_helper((2008, 12, 22), "Monday in the second-to-last week of the "
                                    "year")
        test_helper((1978, 10, 23), "randomly chosen date")
        test_helper((2004, 12, 18), "randomly chosen date")
        test_helper((1978, 10, 23), "year starting and ending on Monday while "
                                        "date not on Sunday or Monday")
        test_helper((1917, 12, 17), "year starting and ending on Monday with "
                                        "a Monday not at the beginning or end "
                                        "of the year")
        test_helper((1917, 12, 31), "Dec 31 on Monday with year starting and "
                                        "ending on Monday")
        test_helper((2007, 01, 07), "First Sunday of 2007")
        test_helper((2007, 01, 14), "Second Sunday of 2007")
        test_helper((2006, 12, 31), "Last Sunday of 2006")
        test_helper((2006, 12, 24), "Second to last Sunday of 2006") 
Example 24
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_dump_bare_datetime(self):
        # This checks that an unwrapped datetime.date object can be handled
        # by the marshalling code.  This can't be done via test_dump_load()
        # since with use_datetime set to 1 the unmarshaller would create
        # datetime objects for the 'datetime[123]' keys as well
        dt = datetime.datetime(2005, 02, 10, 11, 41, 23)
        s = xmlrpclib.dumps((dt,))
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEqual(newdt, dt)
        self.assertEqual(m, None)

        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23')) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_xmlrpc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_datetime_before_1900(self):
        # same as before but with a date before 1900
        dt = datetime.datetime(1, 02, 10, 11, 41, 23)
        s = xmlrpclib.dumps((dt,))
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEqual(newdt, dt)
        self.assertEqual(m, None)

        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23')) 
Example 26
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def weekday(year, month, day):
    """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
       day (1-31)."""
    return datetime.date(year, month, day).weekday() 
Example 27
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def itermonthdays2(self, year, month):
        """
        Like itermonthdates(), but will yield (day number, weekday number)
        tuples. For days outside the specified month the day number is 0.
        """
        for date in self.itermonthdates(year, month):
            if date.month != month:
                yield (0, date.weekday())
            else:
                yield (date.day, date.weekday()) 
Example 28
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def itermonthdays(self, year, month):
        """
        Like itermonthdates(), but will yield day numbers. For days outside
        the specified month the day number is 0.
        """
        for date in self.itermonthdates(year, month):
            if date.month != month:
                yield 0
            else:
                yield date.day 
Example 29
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def monthdatescalendar(self, year, month):
        """
        Return a matrix (list of lists) representing a month's calendar.
        Each row represents a week; week entries are datetime.date values.
        """
        dates = list(self.itermonthdates(year, month))
        return [ dates[i:i+7] for i in range(0, len(dates), 7) ] 
Example 30
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def yeardatescalendar(self, year, width=3):
        """
        Return the data for the specified year ready for formatting. The return
        value is a list of month rows. Each month row contains up to width months.
        Each month contains between 4 and 6 weeks and each week contains 1-7
        days. Days are datetime.date objects.
        """
        months = [
            self.monthdatescalendar(year, i)
            for i in range(January, January+12)
        ]
        return [months[i:i+width] for i in range(0, len(months), width) ] 
Example 31
Project: pyblish-win   Author: pyblish   File: calendar.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def timegm(tuple):
    """Unrelated but handy function to calculate Unix timestamp from GMT."""
    year, month, day, hour, minute, second = tuple[:6]
    days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1
    hours = days*24 + hour
    minutes = hours*60 + minute
    seconds = minutes*60 + second
    return seconds 
Example 32
Project: xadmin_bugfix   Author: vip68   File: base.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, Promise):
            return force_text(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 33
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 34
Project: xadmin_bugfix   Author: vip68   File: models.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 35
Project: xadmin_bugfix   Author: vip68   File: chart.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 36
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 37
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    MIT License 5 votes vote down vote up
def game(self, ctx: Context):
        """
        Gets the date of, and days and months until, CyberStart Game
        """

        await self.countdown('5th November 2019', 'CyberStart Game', ctx) 
Example 38
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    MIT License 5 votes vote down vote up
def essentials(self, ctx: Context):
        """
        Gets the date of, and days and months until, CyberStart Essentials
        """

        await self.countdown('16th December 2019', 'CyberStart Essentials', ctx) 
Example 39
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    MIT License 5 votes vote down vote up
def countdown(self, countdown_target_str: str, stage_name: str, ctx: Context):
        countdown_target = parse(countdown_target_str).date()

        # Get the current date
        today = datetime.date.today()
        time_until_target = relativedelta(countdown_target, today)

        # Given a number of items, determine whether it should be pluralised.
        # Then, return the suffix of 's' if it should be, and '' if it shouldn't.
        def suffix_from_number(num):
            return "" if num == 1 else "s"

        month_or_months = "month" + suffix_from_number(time_until_target.months)
        day_or_days = "day" + suffix_from_number(time_until_target.days)

        month_countdown = f"{time_until_target.months} {month_or_months}"
        day_countdown = f"{time_until_target.days} {day_or_days}"

        # Diable the months component of the countdown when there are no months left
        if time_until_target.months:
            month_and_day_countdown = f"{month_countdown} and {day_countdown}"
        else:
            month_and_day_countdown = day_countdown

        if today > countdown_target:
            await ctx.send(f"{stage_name} has begun!")
            return
        await ctx.send(f"{stage_name} begins on the {countdown_target_str}.\n"
                       f"That's in {month_and_day_countdown}!") 
Example 40
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 5 votes vote down vote up
def sel_time(da, start_date, end_date):
    """Subset a DataArray or Dataset for a given date range.

    Ensures that data are present for full extent of requested range.
    Appends start and end date of the subset to the DataArray.

    Parameters
    ----------
    da : DataArray or Dataset
        data to subset
    start_date : np.datetime64
        start of date interval
    end_date : np.datetime64
        end of date interval

    Returns
    ----------
    da : DataArray or Dataset
        subsetted data

    Raises
    ------
    AssertionError
        if data for requested range do not exist for part or all of
        requested range
    """
    _assert_has_data_for_time(da, start_date, end_date)
    da[SUBSET_START_DATE_STR] = xr.DataArray(start_date)
    da[SUBSET_END_DATE_STR] = xr.DataArray(end_date)
    return da.sel(**{TIME_STR: slice(start_date, end_date)}) 
Example 41
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 5 votes vote down vote up
def infer_year(date):
    """Given a datetime-like object or string infer the year.

    Parameters
    ----------
    date : datetime-like object or str
        Input date

    Returns
    -------
    int

    Examples
    --------
    >>> infer_year('2000')
    2000
    >>> infer_year('2000-01')
    2000
    >>> infer_year('2000-01-31')
    2000
    >>> infer_year(datetime.datetime(2000, 1, 1))
    2000
    >>> infer_year(np.datetime64('2000-01-01'))
    2000
    >>> infer_year(DatetimeNoLeap(2000, 1, 1))
    2000
    >>>
    """
    if isinstance(date, str):
        # Look for a string that begins with four numbers; the first four
        # numbers found are the year.
        pattern = r'(?P<year>\d{4})'
        result = re.match(pattern, date)
        if result:
            return int(result.groupdict()['year'])
        else:
            raise ValueError('Invalid date string provided: {}'.format(date))
    elif isinstance(date, np.datetime64):
        return date.item().year
    else:
        return date.year 
Example 42
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _date_to_unix(arg):
    """Converts a timetuple, integer or datetime object into the seconds from
    epoch in utc.
    """
    if isinstance(arg, datetime):
        arg = arg.utctimetuple()
    elif isinstance(arg, (int, long, float)):
        return int(arg)
    year, month, day, hour, minute, second = arg[:6]
    days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
    hours = days * 24 + hour
    minutes = hours * 60 + minute
    seconds = minutes * 60 + second
    return seconds 
Example 43
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _date_to_unix(arg):
    """Converts a timetuple, integer or datetime object into the seconds from
    epoch in utc.
    """
    if isinstance(arg, datetime):
        arg = arg.utctimetuple()
    elif isinstance(arg, (int, long, float)):
        return int(arg)
    year, month, day, hour, minute, second = arg[:6]
    days = date(year, month, 1).toordinal() - _epoch_ord + day - 1
    hours = days * 24 + hour
    minutes = hours * 60 + minute
    seconds = minutes * 60 + second
    return seconds 
Example 44
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, Promise):
            return force_text(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 45
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 46
Project: django-xadmin   Author: MarkHoo   File: models.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 47
Project: django-xadmin   Author: MarkHoo   File: chart.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 48
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 49
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, Promise):
            return force_text(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 50
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 51
Project: django-xadmin   Author: MarkHoo   File: models.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 52
Project: django-xadmin   Author: MarkHoo   File: chart.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 53
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 54
Project: django-xadmin   Author: MarkHoo   File: base.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, Promise):
            return force_text(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 55
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 56
Project: django-xadmin   Author: MarkHoo   File: models.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(o, datetime.date):
            return o.strftime('%Y-%m-%d')
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, ModelBase):
            return '%s.%s' % (o._meta.app_label, o._meta.model_name)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 57
Project: django-xadmin   Author: MarkHoo   File: chart.py    MIT License 5 votes vote down vote up
def default(self, o):
        if isinstance(o, (datetime.date, datetime.datetime)):
            return calendar.timegm(o.timetuple()) * 1000
        elif isinstance(o, decimal.Decimal):
            return str(o)
        else:
            try:
                return super(JSONEncoder, self).default(o)
            except Exception:
                return smart_text(o) 
Example 58
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 59
Project: calendrino   Author: danstowell   File: calendrino_render.py    GNU General Public License v3.0 5 votes vote down vote up
def _unpack_date_time(dt):
	if isinstance(dt, datetime):
		return (dt.date(), dt.time())
	elif isinstance(dt, date):
		return (dt, None)
	else:
		raise ValueError('Unknown date type') 
Example 60
Project: calendrino   Author: danstowell   File: calendrino_render.py    GNU General Public License v3.0 5 votes vote down vote up
def expand_event(event):
	"expands recurring events into each individual instance"
	if 'RRULE' in event:
		event_start = event['DTSTART'].dt
		dtdelta =  event['DTEND'].dt - event_start
		tz = getattr(event_start, 'tzinfo', None)
		if isinstance(event_start, datetime):
			event_start = event_start.replace(tzinfo=None)

		onerrule = '\n'.join(get_recurrence_lines(event))
		ruleset = rrule.rrulestr(onerrule, dtstart=event_start, forceset=True, ignoretz=True)

		for event_dt_start in ruleset:

			newdate = event_dt_start.date()
			if newdate < startdate:
				continue
			if newdate > enddate:
				return

			newev = deepcopy(event)
			if isinstance(newev['DTSTART'].dt, datetime):
				newev['DTSTART'].dt = event_dt_start.replace(tzinfo=tz)
				newev['DTEND'  ].dt = (event_dt_start + dtdelta).replace(tzinfo=tz)
			else:
				newev['DTSTART'].dt = event_dt_start.date()
				newev['DTEND'  ].dt = event_dt_start.date() + dtdelta

			yield newev
	else:
		yield event 
Example 61
Project: HushUtility   Author: Deathhush   File: StockDataFetcher.py    MIT License 5 votes vote down vote up
def save_daily_bar_to_file(self, dayBars, outputFile):
        resultFile = file(outputFile, 'wb')
        writer = csv.writer(resultFile)
        writer.writerow(['date', 'open', 'high','low','close','volume','amount', 'pre_close', 'adj_factor', 'flag'])
        writer.writerows([dayBarToRow(b) for b in dayBars])
        resultFile.close() 
Example 62
Project: HushUtility   Author: Deathhush   File: StockDataFetcher.py    MIT License 5 votes vote down vote up
def load_daily_df(self, symbol, start, end):
        start_date = datetime.strptime(start, '%Y/%m/%d')
        end_date = datetime.strptime(end, '%Y/%m/%d')
        df = self.load_daily_df_by_year(symbol, start_date.year)
        for i in range(start_date.year+1, end_date.year+1):
            df = df.append(self.load_daily_df_by_year(symbol, i), ignore_index=True)
        df = df[df['date'] > start]
        df = df[df['date'] < end]
        df = df.reset_index(drop=True)

        return df 
Example 63
Project: HushUtility   Author: Deathhush   File: StockDataAnalyzer.py    MIT License 5 votes vote down vote up
def load_daily_df(self, symbol, start, end):
        start_date = datetime.strptime(start, '%Y/%m/%d')
        end_date = datetime.strptime(end, '%Y/%m/%d')
        prefetch_date = start_date - timedelta(days=45)
        df = self.fetcher.load_daily_df(symbol, prefetch_date.strftime('%Y/%m/%d'), end)        

        analyzedFileName = '%s.%s.to.%s.analyzed.csv' % (symbol, start_date.strftime('%Y%m%d'), end_date.strftime('%Y%m%d'))
        analyzedPath = os.path.join(self.workingDir, 'analyzed', analyzedFileName)        
        df = self.analyze(df, analyzedPath)

        df = df[df['date'] >=start]
        df = df.reset_index(drop=True)
        return df 
Example 64
Project: IsThatWho   Author: justanr   File: tmdb.py    MIT License 5 votes vote down vote up
def format_movie_name(movie):
    if movie['release_date']:
        when = date(*map(int, movie['release_date'].split('-')))
        return '{} ({!s})'.format(movie['title'], when.year)
    return movie['title'] 
Example 65
Project: aws-auto-remediate   Author: servian   File: test_securityhub_static.py    GNU General Public License v3.0 5 votes vote down vote up
def test_convert_to_datetime(self, sh):
        assert sh.convert_to_datetime(datetime.date(1999, 12, 31)) == datetime.datetime(
            1999, 12, 31, 0, 0, 0
        ) 
Example 66
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 67
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 68
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 69
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 70
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 71
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: constructor.py    MIT License 5 votes vote down vote up
def construct_yaml_timestamp(self, node):
        value = self.construct_scalar(node)
        match = self.timestamp_regexp.match(node.value)
        values = match.groupdict()
        year = int(values['year'])
        month = int(values['month'])
        day = int(values['day'])
        if not values['hour']:
            return datetime.date(year, month, day)
        hour = int(values['hour'])
        minute = int(values['minute'])
        second = int(values['second'])
        fraction = 0
        if values['fraction']:
            fraction = values['fraction'][:6]
            while len(fraction) < 6:
                fraction += '0'
            fraction = int(fraction)
        delta = None
        if values['tz_sign']:
            tz_hour = int(values['tz_hour'])
            tz_minute = int(values['tz_minute'] or 0)
            delta = datetime.timedelta(hours=tz_hour, minutes=tz_minute)
            if values['tz_sign'] == '-':
                delta = -delta
        data = datetime.datetime(year, month, day, hour, minute, second, fraction)
        if delta:
            data -= delta
        return data 
Example 72
Project: cplot   Author: sunchaoatmo   File: cstoolkit.py    GNU General Public License v3.0 5 votes vote down vote up
def daysbetween(by,bm,bd,ey,em,ed):
   tb=date(by,bm,bd)
   te=date(ey,em,ed)
   td=abs(te-tb).days
   return td; 
Example 73
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 74
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def bind_processor(self, dialect):
        def process(value):
            if type(value) == datetime.date:
                return datetime.datetime(value.year, value.month, value.day)
            else:
                return value
        return process 
Example 75
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def bind_processor(self, dialect):
        def process(value):
            if type(value) == datetime.date:
                return datetime.datetime(value.year, value.month, value.day)
            else:
                return value
        return process 
Example 76
Project: tom-bot   Author: maartenberg   File: doekoe_plugin.py    MIT License 4 votes vote down vote up
def doekoe():
    '''
    Bereken wanneer verschillende uitbetalingen gebeuren.

    De huidige uitbetalingen zijn:
      - SAH Loon: de eerstvolgende 8e van een maand
      - Zorgtoeslag: de eerste werkdag na de 20e
      - Studiefinanciƫring: de laatste werkdag voor de 24e
    '''
    res = ""
    today = date.today()
    next_month = today + relativedelta(months=1)

    # Loon: Eerstvolgende 8e van de maand
    if today.day == 8:
        res += 'Loon is vandaag!\n'
    elif today.day < 8:
        loondag = date(today.year, today.month, 8)
        res += 'Loon komt over {} {}. ({})\n'.format(
            8-today.day, 'dag' if 8-today.day < 2 else 'dagen', loondag.isoformat())
    else:
        loondag = date(next_month.year, next_month.month, 8)
        delta = relativedelta(loondag, today)
        res += 'Loon komt over {} {}. ({})\n'.format(
            delta.days, 'dag' if delta.days < 2 else 'dagen', loondag.isoformat())

    # Zorgtoeslag: eerste werkdag na de 20e
    ztdag = first_weekday_after(date(today.year, today.month, 20))

    if today > ztdag:
        ztdag = first_weekday_after(date(next_month.year, next_month.month, 20))

    if today == ztdag:
        res += 'Zorgtoeslag is vandaag! ({})\n'.format(ztdag.isoformat())
    else:
        delta = relativedelta(ztdag, today)
        res += 'Zorgtoeslag komt over {} {}. ({})\n'.format(
            delta.days, 'dag' if delta.days < 2 else 'dagen', ztdag.isoformat())

    # Stufi: laatste werkdag voor de 24e
    stufidag = last_weekday_before(date(today.year, today.month, 24))

    if today > stufidag:  # volgende maand berekenen
        stufidag = last_weekday_before(date(next_month.year, next_month.month, 24))

    if today == stufidag:
        res += 'Stufi is vandaag! ({})\n'.format(stufidag.isoformat())
    else:
        delta = relativedelta(stufidag, today)
        res += 'Stufi komt over {} {}. ({})\n'.format(
            delta.days, 'dag' if delta.days < 2 else 'dagen', stufidag.isoformat())

    res += '\nAan deze informatie kunnen geen rechten worden ontleend.'
    return res 
Example 77
Project: cyberdisc-bot   Author: CyberDiscovery   File: cyber.py    MIT License 4 votes vote down vote up
def level(self, ctx: Context, base: str, level_num: int, challenge_num: int = 0):
        """
        Gets information about a specific CyberStart Game level and challenge.
        If the date is before the start date of game (15th January 2019) it will redirect to game() instead
        """

        if datetime.date.today() < datetime.date(2019, 1, 15):
            await self.game.callback(self, ctx)
            return

        # Gather data from CyberStart Game.
        with open("cdbot/data/game.json") as f:
            game_docs = load(f)
        # Temporary change to allow old usage method
        if base.isnumeric():
            challenge_num = level_num
            level_num = int(base)
            base = "hq"
        elif challenge_num == 0:
            await ctx.send("Invalid challenge number!")
            return
        # Find out which base the user is refering to.
        for area in BASE_ALIASES.keys():
            if base.lower() in BASE_ALIASES[area]:
                base = area
                break
        else:
            await ctx.send("Unknown base.")
            return

        # Check to see if that many levels are present
        if not 0 < level_num <= len(game_docs[base]):
            await ctx.send("Invalid level number!")
        # Then, check to see if the requested challenge is present
        elif challenge_num not in range(len(game_docs[base][level_num - 1]) + 1):
            await ctx.send("Invalid challenge number!")

        else:
            # Select the needed challenge
            challenge_raw = game_docs[base][level_num - 1][challenge_num - 1]
            challenge_title = challenge_raw["title"]
            challenge_tip = challenge_raw["tips"]
            challenge_text = challenge_raw["description"]
            embed = Embed(
                title=(f"{base} - Level {level_num} Challenge {challenge_num} - {challenge_title}"),
                description=challenge_text,
                colour=0x4262f4
            )
            embed.set_author(
                name="Cyber Discovery",
                icon_url=CYBERDISC_ICON_URL
            )
            embed.set_footer(text="  |  ".join(challenge_tip))

            await ctx.send(embed=embed) 
Example 78
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 4 votes vote down vote up
def _assert_has_data_for_time(da, start_date, end_date):
    """Check to make sure data is in Dataset for the given time range.

    Parameters
    ----------
    da : DataArray
         DataArray with a time variable
    start_date : datetime-like object or str
         start date
    end_date : datetime-like object or str
         end date

    Raises
    ------
    AssertionError
         If the time range is not within the time range of the DataArray

    """
    if isinstance(start_date, str) and isinstance(end_date, str):
        logging.warning(
            'When using strings to specify start and end dates, the check '
            'to determine if data exists for the full extent of the desired '
            'interval is not implemented.  Therefore it is possible that '
            'you are doing a calculation for a lesser interval than you '
            'specified.  If you would like this check to occur, use explicit '
            'datetime-like objects for bounds instead.')
        return

    if RAW_START_DATE_STR in da.coords:
        with warnings.catch_warnings(record=True):
            da_start = da[RAW_START_DATE_STR].values
            da_end = da[RAW_END_DATE_STR].values
    else:
        times = da.time.isel(**{TIME_STR: [0, -1]})
        da_start, da_end = times.values

    message = ('Data does not exist for requested time range: {0} to {1};'
               ' found data from time range: {2} to {3}.')
    # Add tolerance of one second, due to precision of cftime.datetimes
    tol = datetime.timedelta(seconds=1)
    if isinstance(da_start, np.datetime64):
        tol = np.timedelta64(tol, 'ns')
    range_exists = ((da_start - tol) <= start_date and
                    (da_end + tol) >= end_date)
    assert (range_exists), message.format(start_date, end_date,
                                          da_start, da_end) 
Example 79
Project: aospy   Author: spencerahill   File: times.py    Apache License 2.0 4 votes vote down vote up
def maybe_convert_to_index_date_type(index, date):
    """Convert a datetime-like object to the index's date type.

    Datetime indexing in xarray can be done using either a pandas
    DatetimeIndex or a CFTimeIndex.  Both support partial-datetime string
    indexing regardless of the calendar type of the underlying data;
    therefore if a string is passed as a date, we return it unchanged.  If a
    datetime-like object is provided, it will be converted to the underlying
    date type of the index.  For a DatetimeIndex that is np.datetime64; for a
    CFTimeIndex that is an object of type cftime.datetime specific to the
    calendar used.

    Parameters
    ----------
    index : pd.Index
        Input time index
    date : datetime-like object or str
        Input datetime

    Returns
    -------
    date of the type appropriate for the time index of the Dataset
    """
    if isinstance(date, str):
        return date

    if isinstance(index, pd.DatetimeIndex):
        if isinstance(date, np.datetime64):
            return date
        else:
            return np.datetime64(str(date))
    else:
        date_type = index.date_type
        if isinstance(date, date_type):
            return date
        else:
            if isinstance(date, np.datetime64):
                # Convert to datetime.date or datetime.datetime object
                date = date.item()

            if isinstance(date, datetime.date):
                # Convert to a datetime.datetime object
                date = datetime.datetime.combine(
                    date, datetime.datetime.min.time())

            return date_type(date.year, date.month, date.day, date.hour,
                             date.minute, date.second, date.microsecond) 
Example 80
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)}