Python datetime.datetime.fromordinal() Examples

The following are 30 code examples of datetime.datetime.fromordinal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.datetime , or try the search function .
Example #1
Source File: longtermmean.py    From yatsm with MIT License 6 votes vote down vote up
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 
Example #2
Source File: _converter.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #3
Source File: _converter.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #4
Source File: celeb_age.py    From autokeras with MIT License 6 votes vote down vote up
def datenum_to_datetime(datenum):
    """
    Convert Matlab datenum into Python datetime.
    """
    days = datenum % 1
    hours = days % 1 * 24
    minutes = hours % 1 * 60
    seconds = minutes % 1 * 60
    try:
        return (
            datetime.fromordinal(int(datenum))
            + timedelta(days=int(days))
            + timedelta(hours=int(hours))
            + timedelta(minutes=int(minutes))
            + timedelta(seconds=round(seconds))
            - timedelta(days=366)
        )
    except:
        return datenum_to_datetime(700000) 
Example #5
Source File: _converter.py    From coffeegrindsize with MIT License 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #6
Source File: utils.py    From pastas with MIT License 6 votes vote down vote up
def datenum_to_datetime(datenum):
    """
    Convert Matlab datenum into Python datetime.
    Parameters
    ----------
    datenum: float
        date in datenum format

    Returns
    -------
    datetime :
        Datetime object corresponding to datenum.
    """
    days = datenum % 1.
    return datetime.fromordinal(int(datenum)) \
           + timedelta(days=days) - timedelta(days=366) 
Example #7
Source File: _converter.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #8
Source File: converter.py    From Computable with MIT License 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

### Fixed frequency dynamic tick locators and formatters

##### -------------------------------------------------------------------------
#---- --- Locators ---
##### ------------------------------------------------------------------------- 
Example #9
Source File: _converter.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #10
Source File: _converter.py    From twitter-stock-recommendation with MIT License 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #11
Source File: _converter.py    From recruit with Apache License 2.0 6 votes vote down vote up
def _from_ordinal(x, tz=None):
    ix = int(x)
    dt = datetime.fromordinal(ix)
    remainder = float(x) - ix
    hour, remainder = divmod(24 * remainder, 1)
    minute, remainder = divmod(60 * remainder, 1)
    second, remainder = divmod(60 * remainder, 1)
    microsecond = int(1e6 * remainder)
    if microsecond < 10:
        microsecond = 0  # compensate for rounding errors
    dt = datetime(dt.year, dt.month, dt.day, int(hour), int(minute),
                  int(second), microsecond)
    if tz is not None:
        dt = dt.astimezone(tz)

    if microsecond > 999990:  # compensate for rounding errors
        dt += timedelta(microseconds=1e6 - microsecond)

    return dt

# Fixed frequency dynamic tick locators and formatters

# -------------------------------------------------------------------------
# --- Locators ---
# ------------------------------------------------------------------------- 
Example #12
Source File: test_ccdcesque.py    From yatsm with MIT License 6 votes vote down vote up
def test_CCDCesque_changedates(record):
    # Test start, end, and break dates of first two segments
    starts = [dt.strptime('1984-06-04', '%Y-%m-%d'),
              dt.strptime('1999-07-16', '%Y-%m-%d')]
    ends = [dt.strptime('1999-06-30', '%Y-%m-%d'),
            dt.strptime('2003-07-11', '%Y-%m-%d')]
    breaks = [dt.strptime('1999-07-16', '%Y-%m-%d'),
              dt.strptime('2003-07-27', '%Y-%m-%d')]

    for i in range(2):
        assert dt.fromordinal(record[i]['start']) == starts[i]
        assert dt.fromordinal(record[i]['end']) == ends[i]
        assert dt.fromordinal(record[i]['break']) == breaks[i]


# And now for the more hazardous tests on coefficents and RMSE 
Example #13
Source File: TYY_utils.py    From SSR-Net with Apache License 2.0 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #14
Source File: TYY_utils.py    From SSR-Net with Apache License 2.0 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #15
Source File: convert_to_records_multiCPU.py    From Age-Gender-Estimate-TF with MIT License 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #16
Source File: au_dfat_sanctions.py    From opensanctions with MIT License 5 votes vote down vote up
def parse_reference(emitter, reference, rows):
    entity = emitter.make('LegalEntity')
    entity.make_id(reference)
    entity.add('sourceUrl', URL)
    sanction = emitter.make('Sanction')
    sanction.make_id(entity.id)
    sanction.add('authority', 'Australian Department of Foreign Affairs and Trade Consolidated Sanctions')  # noqa
    sanction.add('entity', entity)

    for row in rows:
        if row.pop('type') == 'Individual':
            entity.schema = model.get('Person')

        name = row.pop('name_of_individual_or_entity', None)
        if row.pop('name_type') == 'aka':
            entity.add('alias', name)
        else:
            entity.add('name', name)

        entity.add('address', row.pop('address'))
        entity.add('notes', row.pop('additional_information'))
        sanction.add('program', row.pop('committees'))
        nationality = normalize_country(row.pop('citizenship'))
        entity.add('nationality', nationality, quiet=True)
        entity.add('birthDate', row.pop('date_of_birth'), quiet=True)
        entity.add('birthPlace', row.pop('place_of_birth'), quiet=True)
        entity.add('status', row.pop('listing_information'), quiet=True)

        control_date = int(row.pop('control_date'))
        base_date = datetime(1900, 1, 1).toordinal()
        dt = datetime.fromordinal(base_date + control_date - 2)
        sanction.add('modifiedAt', dt.date())
        entity.add('modifiedAt', dt.date())

    emitter.emit(entity)
    emitter.emit(sanction) 
Example #17
Source File: convert_to_records.py    From Age-Gender-Estimate-TF with MIT License 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #18
Source File: test_ccalendar.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def test_get_day_of_year_dt():
    dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
    result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)

    expected = (dt - dt.replace(month=1, day=1)).days + 1
    assert result == expected 
Example #19
Source File: TYY_utils.py    From MaskInsightface with Apache License 2.0 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    # assume the photo was taken in the middle of the year
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #20
Source File: test_ccalendar.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def test_get_day_of_year():
    assert ccalendar.get_day_of_year(2001, 3, 1) == 60
    assert ccalendar.get_day_of_year(2004, 3, 1) == 61
    assert ccalendar.get_day_of_year(1907, 12, 31) == 365
    assert ccalendar.get_day_of_year(2004, 12, 31) == 366

    dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
    result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)
    expected = (dt - dt.replace(month=1, day=1)).days + 1
    assert result == expected 
Example #21
Source File: run.py    From Generative-Adversarial-Networks-Projects with MIT License 5 votes vote down vote up
def calculate_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))

    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #22
Source File: utils.py    From age-gender-estimator-keras with MIT License 5 votes vote down vote up
def calc_age(taken, dob):
    birth = datetime.fromordinal(max(int(dob) - 366, 1))
    if birth.month < 7:
        return taken - birth.year
    else:
        return taken - birth.year - 1 
Example #23
Source File: annotation_imdb_keras.py    From YoloKerasFaceDetection with MIT License 5 votes vote down vote up
def calc_age(taken, dob):
	birth = datetime.fromordinal(max(int(dob) - 366, 1))
	if birth.month < 7:
		return taken - birth.year
	else:
		return taken - birth.year - 1 
Example #24
Source File: test_behavior.py    From pendulum with MIT License 5 votes vote down vote up
def test_fromordinal():
    assert datetime.fromordinal(730120) == pendulum.DateTime.fromordinal(730120) 
Example #25
Source File: test_ccalendar.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def test_get_day_of_year_dt():
    dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
    result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)

    expected = (dt - dt.replace(month=1, day=1)).days + 1
    assert result == expected 
Example #26
Source File: adultswim.py    From holo with MIT License 5 votes vote down vote up
def _digest_episode(feed_episode):
    debug("Digesting episode")

    name = feed_episode.find("h4", itemprop="name", class_="episode__title").text
    link = feed_episode.find("a", itemprop="url", class_="episode__link").href
    num = int(feed_episode.find("meta", itemprop="episodeNumber")["content"])

    date_string = feed_episode.find("meta", itemprop="dateCreated")["content"]
    date = datetime.fromordinal(dateutil.parser.parse(date_string).toordinal())

    return Episode(num, name, link, date) 
Example #27
Source File: adultswim.py    From holo with MIT License 5 votes vote down vote up
def _is_valid_episode(episode_data, show_key):
    # Don't check old episodes (possible wrong season !)
    date_string = episode_data.find("meta", itemprop="dateCreated")["content"]
    date = datetime.fromordinal(dateutil.parser.parse(date_string).toordinal())

    if date > datetime.utcnow():
	    return False

    date_diff = datetime.utcnow() - date
    if date_diff >= timedelta(days=2):
	    debug("  Episode too old")
	    return False

    return True 
Example #28
Source File: test_dates.py    From airflow with Apache License 2.0 5 votes vote down vote up
def test_days_ago(self):
        today = pendulum.today()
        today_midnight = pendulum.instance(datetime.fromordinal(today.date().toordinal()))

        self.assertTrue(dates.days_ago(0) == today_midnight)

        self.assertTrue(dates.days_ago(100) == today_midnight + timedelta(days=-100))

        self.assertTrue(dates.days_ago(0, hour=3) == today_midnight + timedelta(hours=3))
        self.assertTrue(dates.days_ago(0, minute=3) == today_midnight + timedelta(minutes=3))
        self.assertTrue(dates.days_ago(0, second=3) == today_midnight + timedelta(seconds=3))
        self.assertTrue(dates.days_ago(0, microsecond=3) == today_midnight + timedelta(microseconds=3)) 
Example #29
Source File: test_ccalendar.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_get_day_of_year():
    assert ccalendar.get_day_of_year(2001, 3, 1) == 60
    assert ccalendar.get_day_of_year(2004, 3, 1) == 61
    assert ccalendar.get_day_of_year(1907, 12, 31) == 365
    assert ccalendar.get_day_of_year(2004, 12, 31) == 366

    dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
    result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)
    expected = (dt - dt.replace(month=1, day=1)).days + 1
    assert result == expected 
Example #30
Source File: test_ccalendar.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_get_day_of_year_dt():
    dt = datetime.fromordinal(1 + np.random.randint(365 * 4000))
    result = ccalendar.get_day_of_year(dt.year, dt.month, dt.day)

    expected = (dt - dt.replace(month=1, day=1)).days + 1
    assert result == expected