Python datetime.date 模块,fromordinal() 实例源码

我们从Python开源项目中,提取了以下27个代码示例,用于说明如何使用datetime.date.fromordinal()

项目:anime_scrapers    作者:jQwotos    | 项目源码 | 文件源码
def need_to_download(self):
        try:
            with open(INFO_FILE, "r") as f:
                data = f.readline()
                if len(data) > 0:
                    last_download = date.fromordinal(int(data))
                    time_delta = date.today() - last_download
                    if time_delta.days > 7:
                        return True
                    else:
                        return False
                else:
                    return True
        except FileNotFoundError:
            return True
        return False
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _unconvert_index(data, kind, encoding=None):
    kind = _ensure_decoded(kind)
    if kind == u('datetime64'):
        index = DatetimeIndex(data)
    elif kind == u('timedelta64'):
        index = TimedeltaIndex(data)
    elif kind == u('datetime'):
        index = np.asarray([datetime.fromtimestamp(v) for v in data],
                           dtype=object)
    elif kind == u('date'):
        try:
            index = np.asarray(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.asarray(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u('integer'), u('float')):
        index = np.asarray(data)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding)
    elif kind == u('object'):
        index = np.asarray(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index
项目:epicord-bot    作者:Epicord    | 项目源码 | 文件源码
def eightdate(self, *args: str):
        """Generate a random date."""
        ord_today = date.today().toordinal()
        ans = date.today()
        if len(args) > 0:
            yearlist = [int(x) for x in args if x.isdigit()]
            for item in yearlist:
                if item > 9999 or item < 1:
                    await self.bot.reply("ERROR: Years must be 1-9999.")
        else:
            ans = date.fromordinal(random.randint(ORDMIN, ORDMAX))
        if (len(yearlist) == 0):
            ans = date.fromordinal(random.randint(ord_today, ORDMAX))
        elif (len(yearlist) == 1):
            ord_arg = date.toordinal(date(yearlist[0], 12, 31))
            if ord_arg < ord_today:
                ans = date.fromordinal(random.randint(ord_arg, ord_today))
            else:
                ans = date.fromordinal(random.randint(ord_today, ord_arg))
        elif (len(yearlist) == 2):
            ord_argmin = date.toordinal(date(yearlist[0], 1, 1))
            ord_argmax = date.toordinal(date(yearlist[1], 12, 31))
            ans = date.fromordinal(random.randint(ord_argmin, ord_argmax))

        await self.bot.reply(ans.strftime("%b. %d, %Y"))
项目:persiantools    作者:mhajiloo    | 项目源码 | 文件源码
def __add__(self, other):
        if not isinstance(other, timedelta):
            return NotImplemented

        delta = timedelta(self.toordinal(),
                          hours=self._hour,
                          minutes=self._minute,
                          seconds=self._second,
                          microseconds=self._microsecond)
        delta += other
        hour, rem = divmod(delta.seconds, 3600)
        minute, second = divmod(rem, 60)

        if 0 < delta.days <= _MAXORDINAL:
            return JalaliDateTime.combine(JalaliDate.fromordinal(delta.days),
                                          _time(hour, minute, second,
                                                delta.microseconds,
                                                tzinfo=self._tzinfo))

        raise OverflowError("result out of range")
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the date corresponding to the proleptic Gregorian ordinal.

         January 1 of year 1 has ordinal 1. ValueError is raised unless
         1 <= ordinal <= date.max.toordinal().
         For any date d, date.fromordinal(d.toordinal()) == d.
         """
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def toordinal():
        """Return the proleptic Gregorian ordinal of the date

        January 1 of year 1 has ordinal 1. For any date object d,
        date.fromordinal(d.toordinal()) == d.
        """
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the datetime from the proleptic Gregorian ordinal.

        January 1 of year 1 has ordinal 1. ValueError is raised unless
        1 <= ordinal <= datetime.max.toordinal().
        The hour, minute, second and microsecond of the result are all 0, and
        tzinfo is None.
        """
项目:flask-bitmapist    作者:cuttlesoft    | 项目源码 | 文件源码
def random_date(starting_date=None):
    starting_date = starting_date or earliest
    # ordinal dates are easier to pick random between
    start_date = starting_date.toordinal()
    end_date = now.toordinal()
    return date.fromordinal(randint(start_date, end_date))
项目:pendulum    作者:sdispater    | 项目源码 | 文件源码
def test_fromordinal(self):
        self.assertEqual(date.fromordinal(730120), Date.fromordinal(730120))
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the date corresponding to the proleptic Gregorian ordinal.

         January 1 of year 1 has ordinal 1. ValueError is raised unless
         1 <= ordinal <= date.max.toordinal().
         For any date d, date.fromordinal(d.toordinal()) == d.
         """
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def toordinal():
        """Return the proleptic Gregorian ordinal of the date

        January 1 of year 1 has ordinal 1. For any date object d,
        date.fromordinal(d.toordinal()) == d.
        """
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the datetime from the proleptic Gregorian ordinal.

        January 1 of year 1 has ordinal 1. ValueError is raised unless
        1 <= ordinal <= datetime.max.toordinal().
        The hour, minute, second and microsecond of the result are all 0, and
        tzinfo is None.
        """
项目:alexa-apple-calendar    作者:zanderxyz    | 项目源码 | 文件源码
def fromordinal(cls, ordinal):
        """Return the week corresponding to the proleptic Gregorian ordinal,
        where January 1 of year 1 starts the week with ordinal 1.
        """
        if ordinal < 1:
            raise ValueError("ordinal must be >= 1")
        return super(Week, cls).__new__(cls, *(date.fromordinal((ordinal-1) * 7 + 1).isocalendar()[:2]))
项目:alexa-apple-calendar    作者:zanderxyz    | 项目源码 | 文件源码
def __add__(self, other):
        """Adding integers to a Week gives the week that many number of weeks into the future.
        Adding with datetime.timedelta is also supported.
        """
        if isinstance(other, timedelta):
            other = other.days // 7
        return self.__class__.fromordinal(self.toordinal() + other)
项目:XternSlackBot    作者:brubakbd    | 项目源码 | 文件源码
def verify_pizzas(pizzas, user):
    num_pizzas = pizzas['numPizzas'] * len(pizzas['users'])

    sent_pizzas = db_get(user, 'given')
    last_day_given = db_get(user, 'lastDayGiven')
    if last_day_given is not None and (date.today() - date.fromordinal(last_day_given)).days > 0 or sent_pizzas is None:
        sent_pizzas = 0

    return sent_pizzas + num_pizzas <= 5
项目:kisqpy    作者:pkulev    | 项目源码 | 文件源码
def get_random_date(start, end):
    """Random date from datetime.date range.

    :param datetime.date start: left limit
    :param datetime.date end: right limit
    :return: random datetime.date from range
    """

    return date.fromordinal(random.randint(start.toordinal(), end.toordinal()))
项目:AskTanmay-NLQA-System-    作者:tanmayb123    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the date corresponding to the proleptic Gregorian ordinal.

         January 1 of year 1 has ordinal 1. ValueError is raised unless
         1 <= ordinal <= date.max.toordinal().
         For any date d, date.fromordinal(d.toordinal()) == d.
         """
项目:AskTanmay-NLQA-System-    作者:tanmayb123    | 项目源码 | 文件源码
def toordinal():
        """Return the proleptic Gregorian ordinal of the date

        January 1 of year 1 has ordinal 1. For any date object d,
        date.fromordinal(d.toordinal()) == d.
        """
项目:AskTanmay-NLQA-System-    作者:tanmayb123    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the datetime from the proleptic Gregorian ordinal.

        January 1 of year 1 has ordinal 1. ValueError is raised unless
        1 <= ordinal <= datetime.max.toordinal().
        The hour, minute, second and microsecond of the result are all 0, and
        tzinfo is None.
        """
项目:dbas    作者:hhucn    | 项目源码 | 文件源码
def test_python_datetime_pretty_print(self):
        # datetime corresponding to Gregorian ordinal
        d = date.fromordinal(736132)

        # Verify, that if 'lang' is 'de' format of date is 'month. year'
        self.assertEqual(lib.python_datetime_pretty_print(ts=d, lang='de'), 'Jun. 2016')

        # Verify, that if 'lang' is not 'de' format of date is 'day. month.'
        self.assertEqual(lib.python_datetime_pretty_print(ts=d, lang='en'), '17. Jun.')

        self.assertEqual(lib.python_datetime_pretty_print(ts='2016-01-01', lang=''), '01. Jan.')
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the date corresponding to the proleptic Gregorian ordinal.

         January 1 of year 1 has ordinal 1. ValueError is raised unless
         1 <= ordinal <= date.max.toordinal().
         For any date d, date.fromordinal(d.toordinal()) == d.
         """
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def toordinal():
        """Return the proleptic Gregorian ordinal of the date

        January 1 of year 1 has ordinal 1. For any date object d,
        date.fromordinal(d.toordinal()) == d.
        """
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def fromordinal(ordinal):
        """Return the datetime from the proleptic Gregorian ordinal.

        January 1 of year 1 has ordinal 1. ValueError is raised unless
        1 <= ordinal <= datetime.max.toordinal().
        The hour, minute, second and microsecond of the result are all 0, and
        tzinfo is None.
        """
项目:persiantools    作者:mhajiloo    | 项目源码 | 文件源码
def fromordinal(cls, n):
        return cls(date.fromordinal(n + 226894))
项目:persiantools    作者:mhajiloo    | 项目源码 | 文件源码
def __add__(self, other):
        if isinstance(other, timedelta):
            o = self.toordinal() + other.days

            if 0 < o <= _MAXORDINAL:
                return JalaliDate.fromordinal(o)

            raise OverflowError("result out of range")

        return NotImplemented
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def convert(self, values, nan_rep, encoding):
        """set the data from this selection (and convert to the correct dtype
        if we can)
        """

        try:
            values = values[self.cname]
        except:
            pass
        self.set_data(values)

        # use the meta if needed
        meta = _ensure_decoded(self.meta)

        # convert to the correct dtype
        if self.dtype is not None:
            dtype = _ensure_decoded(self.dtype)

            # reverse converts
            if dtype == u('datetime64'):

                # recreate with tz if indicated
                self.data = _set_tz(self.data, self.tz, coerce=True)

            elif dtype == u('timedelta64'):
                self.data = np.asarray(self.data, dtype='m8[ns]')
            elif dtype == u('date'):
                try:
                    self.data = np.asarray(
                        [date.fromordinal(v) for v in self.data], dtype=object)
                except ValueError:
                    self.data = np.asarray(
                        [date.fromtimestamp(v) for v in self.data],
                        dtype=object)
            elif dtype == u('datetime'):
                self.data = np.asarray(
                    [datetime.fromtimestamp(v) for v in self.data],
                    dtype=object)

            elif meta == u('category'):

                # we have a categorical
                categories = self.metadata
                self.data = Categorical.from_codes(self.data.ravel(),
                                                   categories=categories,
                                                   ordered=self.ordered)

            else:

                try:
                    self.data = self.data.astype(dtype, copy=False)
                except:
                    self.data = self.data.astype('O', copy=False)

        # convert nans / decode
        if _ensure_decoded(self.kind) == u('string'):
            self.data = _unconvert_string_array(
                self.data, nan_rep=nan_rep, encoding=encoding)

        return self
项目:wa    作者:wateraccounting    | 项目源码 | 文件源码
def Convert_nc_to_tiff(input_nc, output_folder):
    """
    This function converts the nc file into tiff files

    Keyword Arguments:
    input_nc -- name, name of the adf file
    output_folder -- Name of the output tiff file
    """
    from datetime import date
    import wa.General.raster_conversions as RC

    #All_Data = RC.Open_nc_array(input_nc)

    if type(input_nc) == str:
        nc = netCDF4.Dataset(input_nc)
    elif type(input_nc) == list:
        nc = netCDF4.MFDataset(input_nc)

    Var = nc.variables.keys()[-1]
    All_Data = nc[Var]

    geo_out, epsg, size_X, size_Y, size_Z, Time = RC.Open_nc_info(input_nc)  

    if epsg == 4326:
        epsg = 'WGS84'

    # Create output folder if needed
    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    for i in range(0,size_Z):
        if not Time == -9999:
            time_one = Time[i]
            d = date.fromordinal(time_one)
            name = os.path.splitext(os.path.basename(input_nc))[0]
            nameparts = name.split('_')[0:-2]
            name_out = os.path.join(output_folder, '_'.join(nameparts) + '_%d.%02d.%02d.tif' %(d.year, d.month, d.day))
            Data_one = All_Data[i,:,:]
        else:
            name=os.path.splitext(os.path.basename(input_nc))[0]
            name_out = os.path.join(output_folder, name + '.tif')
            Data_one = All_Data[:,:]


        Save_as_tiff(name_out, Data_one, geo_out, epsg)

    return()