Python datetime.datetime.fromordinal() Examples

The following are code examples for showing how to use datetime.datetime.fromordinal(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: incubator-airflow-old   Author: apache   File: test_dates.py    (license) View Source Project 6 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 2
Project: PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda   Author: SignalMedia   File: converter.py    (license) View Source Project 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
Project: lazysusan   Author: verypossible   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def last_user_difference(session, dob):
    last_date = session.get(DOB_KEY)
    if not last_date:
        return ''

    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." 
Example 4
Project: Thymus-timeseries   Author: sidorof   File: timeseries.py    (license) View Source Project 6 votes vote down vote up
def get_datetime(self, date):
        """
        This function returns a date as a datetime object.
        This takes into account the type of date stored in dseries.

        Usage:
            self.get_datetime(date)
        """
        date_series_type = self.get_date_series_type()
        if date_series_type == TS_ORDINAL:
            return datetime.fromordinal(date)
        elif date_series_type == TS_TIMESTAMP:
            return datetime.fromtimestamp(date)
        else:
            raise ValueError("Unknown, dateseries type. %s" % (
                date_series_type)) 
Example 5
Project: pendulum   Author: sdispater   File: test_behavior.py    (license) View Source Project 5 votes vote down vote up
def test_fromordinal(self):
        self.assertEqual(datetime.fromordinal(730120), pendulum.fromordinal(730120)) 
Example 6
Project: pygeotools   Author: dshean   File: timelib.py    (license) View Source Project 5 votes vote down vote up
def mat2dt(o):
    """Convert Matlab ordinal to Python datetime

    Need to account for AD 0 and AD 1 discrepancy between the two: http://sociograph.blogspot.com/2011/04/how-to-avoid-gotcha-when-converting.html
    
    python_datetime = datetime.fromordinal(int(o)) + timedelta(days=o%1) - timedelta(days = 366)
    """
    return o2dt(o) - timedelta(days=366)

#Python datetime to matlab ordinal 
Example 7
Project: pygeotools   Author: dshean   File: timelib.py    (license) View Source Project 5 votes vote down vote up
def o2dt(o):
    """Convert Python ordinal to datetime
    """
    #omod = np.modf(o)
    #return datetime.fromordinal(int(omod[1])) + timedelta(days=omod[0])
    #Note: num2date returns dt or list of dt
    #This funciton should always return a list
    #return np.array(matplotlib.dates.num2date(o))
    return matplotlib.dates.num2date(o)

#Return integer DOY (julian) 
Example 8
Project: reahl   Author: reahl   File: webdeclarative.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, **kwargs):
        self.generate_salt()
        self.last_activity = datetime.fromordinal(1)
        self.set_idle_lifetime(False)
        super(UserSession, self).__init__(**kwargs) 
Example 9
Project: lenuage   Author: laboiteproject   File: models.py    (license) View Source Project 5 votes vote down vote up
def update_data(self):
        # TODO: handle whole day events, display multiple events
        now = timezone.now()
        tonight = now.replace(hour=23, minute=59)

        self.dtstart = None
        self.summary = None

        calendar = Calendar()
        r = requests.get(self.ics_url)

        calendar = calendar.from_ical(r.text)

        for event in calendar.walk():
            if event.get('dtstart') and event.get('dtend'):
                dtstart = event.get('dtstart').dt
                dtend = event.get('dtend').dt
                if not isinstance(dtstart, datetime) or not isinstance(dtend, datetime):
                    dtstart = datetime.fromordinal(dtstart.toordinal())
                    dtend = datetime.fromordinal(dtend.toordinal())
                try:
                    dtstart = timezone.localtime(dtstart, timezone.utc)
                    dtend = timezone.localtime(dtend, timezone.utc)
                except ValueError:
                    dtstart = dtstart.replace(tzinfo=timezone.utc)
                    dtend = dtend.replace(tzinfo=timezone.utc)
                if now <= dtend <= tonight:
                    dtstart = timezone.localtime(dtstart, pytz.timezone('Europe/Paris'))
                    self.dtstart = formats.time_format(dtstart, 'TIME_FORMAT')
                    self.summary = str(unidecode.unidecode(event.get('summary')))
        self.save() 
Example 10
Project: Thymus-timeseries   Author: sidorof   File: timeseries.py    (license) View Source Project 5 votes vote down vote up
def datetime_series(self):
        """
        This function returns the dateseries converted to a series of
        datetime objects.
        """
        if self.get_date_series_type() == TS_ORDINAL:
            return [datetime.fromordinal(int(i)) for i in self.dseries]
        elif self.get_date_series_type() == TS_TIMESTAMP:
            return [datetime.fromtimestamp(int(i)) for i in self.dseries]
        else:
            raise ValueError("timeseries must have a defined frequency") 
Example 11
Project: Thymus-timeseries   Author: sidorof   File: timeseries.py    (license) View Source Project 5 votes vote down vote up
def fmt_date(numericdate, dt_type, dt_fmt=None):
        """
        This static method accepts a date and converts it to
        the format used in the timeseries.
        """
        if dt_type == TS_ORDINAL:
            if dt_fmt is None:
                dt_fmt = FMT_DATE
            return datetime.fromordinal(int(numericdate)).strftime(dt_fmt)
        elif dt_type == TS_TIMESTAMP:
            if dt_fmt is None:
                dt_fmt = FMT_IDATE
            return datetime.fromtimestamp(numericdate).strftime(dt_fmt)
        else:
            raise ValueError("Unknown dt_type: %s" % dt_type)