How to use the datetime.datetime.fromordinal function in DateTime

To help you get started, we’ve selected a few DateTime examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ceholden / yatsm / sandbox / phenology / phenology.py View on Github external
def ordinal2yeardoy(ordinal):
    """ Convert ordinal dates to two arrays of year and doy

    Args:
      ordinal (np.ndarray): ordinal dates

    Returns:
      np.ndarray: nobs x 2 np.ndarray containing the year and DOY for each
        ordinal date

    """
    _date = [dt.fromordinal(_d) for _d in ordinal]
    yeardoy = np.empty((ordinal.size, 2), dtype=np.uint16)
    yeardoy[:, 0] = np.array([int(_d.strftime('%Y')) for _d in _date])
    yeardoy[:, 1] = np.array([int(_d.strftime('%j')) for _d in _date])

    return yeardoy
github harveywwu / pyktrader / newagent.py View on Github external
self.cur_min[inst]['openInterest'] = last_tick.openInterest
                self.min_switch(inst)

            if self.cur_day[inst]['close'] > 0:
                mysqlaccess.insert_daily_data_to_df(self.day_data[inst], self.cur_day[inst])
                df = self.day_data[inst]
                for fobj in self.day_data_func:
                    fobj.rfunc(df)
                if self.save_flag:
                    mysqlaccess.insert_daily_data('fut_daily', inst, self.cur_day[inst])
            
            self.tick_data[inst] = []
            self.cur_min[inst] = dict([(item, 0) for item in min_data_list])
            self.cur_day[inst] = dict([(item, 0) for item in day_data_list])
            self.cur_day[inst]['date'] = self.scur_day
            self.cur_min[inst]['datetime'] = datetime.datetime.fromordinal(self.scur_day.toordinal())
        if self.trader != None:
            self.save_eod_positions()
            self.etrades = []
            self.ref2order = {}
        for strat in self.strategies:
            strat.day_finalize()
github olemb / dbfread / dbfread / field_parser.py View on Github external
# that could be used when working with different calendars and to
        # unify different historical chronologies." - wikipedia.org

        # Offset from julian days (used in the file) to proleptic Gregorian
        # ordinals (used by the datetime module)
        offset = 1721425  # Todo: will this work?

        if data.strip():
            # Note: if the day number is 0, we return None
            # I've seen data where the day number is 0 and
            # msec is 2 or 4. I think we can safely return None for those.
            # (At least I hope so.)
            #
            day, msec = struct.unpack('
github CouchPotato / CouchPotatoServer / libs / apscheduler / util.py View on Github external
def convert_to_datetime(input):
    """
    Converts the given object to a datetime object, if possible.
    If an actual datetime object is passed, it is returned unmodified.
    If the input is a string, it is parsed as a datetime.

    Date strings are accepted in three different forms: date only (Y-m-d),
    date with time (Y-m-d H:M:S) or with date+time with microseconds
    (Y-m-d H:M:S.micro).

    :rtype: datetime
    """
    if isinstance(input, datetime):
        return input
    elif isinstance(input, date):
        return datetime.fromordinal(input.toordinal())
    elif isinstance(input, basestring):
        m = _DATE_REGEX.match(input)
        if not m:
            raise ValueError('Invalid date string')
        values = [(k, int(v or 0)) for k, v in m.groupdict().items()]
        values = dict(values)
        return datetime(**values)
    raise TypeError('Unsupported input type: %s' % type(input))
github verypossible / lazysusan / examples / age_difference / Age / callbacks / __init__.py View on Github external
def last_user_difference(session, dob):
    last_date = session.get(DOB_KEY)
    if last_date:
        last_date = datetime.fromordinal(last_date)
        old_or_younger = "same"
        if dob > last_date:
            old_or_younger = "younger"
            diff = relativedelta(dob, last_date)
        elif dob < last_date:
            old_or_younger = "older"
            diff = relativedelta(last_date, dob)

        if old_or_younger != "same":
            return "You are %s years, %s months, %s days %s than the last user." % (
                    diff.years, diff.months, diff.days, old_or_younger)
        return "You have the same birthday as the last user."
github insarlab / MintPy / mintpy / legacy / gui / tsview_dev.py View on Github external
def read_timeseries_info():
    global atr, k, h5, dateList, tims, date_num, inps

    atr = readfile.read_attribute(inps.timeseries_file)
    k = atr['FILE_TYPE']
    print(('input file is '+k+': '+inps.timeseries_file))
    if not k in ['timeseries','GIANT_TS']:
        raise ValueError('Only timeseries file is supported!')

    h5 = h5py.File(inps.timeseries_file,'r')
    if k in ['GIANT_TS']:
        dateList = [dt.fromordinal(int(i)).strftime('%Y%m%d') for i in h5['dates'][:].tolist()]
    else:
        dateList = timeseries(inps.timeseries_file).get_date_list()
    date_num = len(dateList)
    inps.dates, tims = ptime.date_list2vector(dateList)
github priestc / moneywagon / moneywagon / supply_estimator.py View on Github external
def estimate_height_from_date(self, at_time):
        if not hasattr(at_time, 'hour'):
            at_time = datetime.datetime.fromordinal(at_time.toordinal())
        minutes = (at_time - self.genesis_date).total_seconds() / 60.0
        target_block = int(minutes / self.minutes_per_block)

        if self.blocktime_adjustments:
            new_block = 0
            previous_minutes_per_block = self.minutes_per_block
            minutes_since_genesis = 0

            for minutes_since_last_adjustment, new_minutes_per_block in self.block_adjustment_in_minutes:
                if minutes_since_last_adjustment < minutes:
                    this_blocks = minutes_since_last_adjustment / previous_minutes_per_block
                    new_block += this_blocks
                else:
                    remainder_blocks = (minutes - minutes_since_genesis) / previous_minutes_per_block
                    new_block += remainder_blocks
                    break
github jeeftor / alfredToday / src / lib / dateutil / relativedelta.py View on Github external
microseconds=(other.microseconds +
                                               self.microseconds),
                                 leapdays=other.leapdays or self.leapdays,
                                 year=other.year or self.year,
                                 month=other.month or self.month,
                                 day=other.day or self.day,
                                 weekday=other.weekday or self.weekday,
                                 hour=other.hour or self.hour,
                                 minute=other.minute or self.minute,
                                 second=other.second or self.second,
                                 microsecond=(other.microsecond or
                                              self.microsecond))
        if not isinstance(other, datetime.date):
            raise TypeError("unsupported type for add operation")
        elif self._has_time and not isinstance(other, datetime.datetime):
            other = datetime.datetime.fromordinal(other.toordinal())
        year = (self.year or other.year)+self.years
        month = self.month or other.month
        if self.months:
            assert 1 <= abs(self.months) <= 12
            month += self.months
            if month > 12:
                year += 1
                month -= 12
            elif month < 1:
                year -= 1
                month += 12
        day = min(calendar.monthrange(year, month)[1],
                  self.day or other.day)
        repl = {"year": year, "month": month, "day": day}
        for attr in ["hour", "minute", "second", "microsecond"]:
            value = getattr(self, attr)
github flika-org / flika / plugins / behavior / tifffile.py View on Github external
def datetime_from_timestamp(n, epoch=datetime.datetime.fromordinal(693594)):
    """Return datetime object from timestamp in Excel serial format.

    Examples
    --------
    >>> datetime_from_timestamp(40237.029999999795)
    datetime.datetime(2010, 2, 28, 0, 43, 11, 999982)

    """
    return epoch + datetime.timedelta(n)
github jazzband / tablib / src / tablib / packages / dbfpy / utils.py View on Github external
by the time.time() call;
        sequence:
            assuming (year, month, day, ...) sequence;

    Additionally, if ``value`` has callable ``ticks`` attribute,
    it will be used and result of the called would be treated
    as a timestamp value.

    """
    if value is None:
        # use current value
        return datetime.datetime.today()
    if isinstance(value, datetime.datetime):
        return value
    if isinstance(value, datetime.date):
        return datetime.datetime.fromordinal(value.toordinal())
    if isinstance(value, (int, float)):
        # value is a timestamp
        return datetime.datetime.fromtimestamp(value)
    if isinstance(value, str):
        raise NotImplementedError("Strings aren't currently implemented")
    if hasattr(value, "__getitem__"):
        # a sequence (assuming date/time tuple)
        return datetime.datetime(*tuple(value)[:6])
    return datetime.datetime.fromtimestamp(value.ticks())