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))
python类fromordinal()的实例源码
converter.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
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 ---
# -------------------------------------------------------------------------
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."
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))
def test_fromordinal(self):
self.assertEqual(datetime.fromordinal(730120), pendulum.fromordinal(730120))
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
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)
def __init__(self, **kwargs):
self.generate_salt()
self.last_activity = datetime.fromordinal(1)
self.set_idle_lifetime(False)
super(UserSession, self).__init__(**kwargs)
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()
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")
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)