A date flooring function.

  Returns the closest datetime to the current one that aligns to timeframe.
  For example, _date_trunc('2014-08-13 05:00:00', DateTrunc.Unit.MONTH)
  will return a Kronos time representing 2014-08-01 00:00:00.
14572
def _date_trunc(value, timeframe):
  
  if isinstance(value, types.StringTypes):
    value = parse(value)
    return_as_str = True
  else:
    value = kronos_time_to_datetime(value)
    return_as_str = False
  timeframes = {
    DateTrunc.Unit.SECOND: (lambda dt:
                            dt - timedelta(microseconds=dt.microsecond)),
    DateTrunc.Unit.MINUTE: (lambda dt:
                            dt - timedelta(seconds=dt.second,
                                           microseconds=dt.microsecond)),
    DateTrunc.Unit.HOUR: (lambda dt:
                          dt - timedelta(minutes=dt.minute,
                                         seconds=dt.second,
                                         microseconds=dt.microsecond)),
    DateTrunc.Unit.DAY: lambda dt: dt.date(),
    DateTrunc.Unit.WEEK: lambda dt: dt.date() - timedelta(days=dt.weekday()),
    DateTrunc.Unit.MONTH: lambda dt: datetime(dt.year, dt.month, 1),
    DateTrunc.Unit.YEAR: lambda dt: datetime(dt.year, 1, 1)
  }
  value = timeframes[timeframe](value)
  if return_as_str:
    return value.isoformat()
  return datetime_to_kronos_time(value)
1141083
def truncate_date_to_first_of_month(
        dt: Optional[DateLikeType]) -> Optional[DateLikeType]:
    
    if dt is None:
        return None
    return dt.replace(day=1)
1234698
def date_struct_nn(year, month, day, tz="UTC"):
    
    if not day:
        day = 1
    if not month:
        month = 1
    return date_struct(year, month, day, tz)
209399
def move_datetime_month(dt, direction, num_shifts):
    
    delta = relativedelta(months=+num_shifts)
    return _move_datetime(dt, direction, delta)
964796
function jdnToGregorian(jdn, JD_OFFSET = JD_EPOCH_OFFSET_GREGORIAN, leapYear = isGregorianLeap) {
  const nMonths = 12;
  const monthDays = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  const r2000 = mod((jdn - JD_OFFSET), 730485);
  const r400 = mod((jdn - JD_OFFSET), 146097);
  const r100 = mod(r400, 36524);
  const r4 = mod(r100, 1461);

  let n = mod(r4, 365) + 365 * Math.floor(r4 / 1460);
  const s = Math.floor(r4 / 1095);

  const aprime = 400 * Math.floor((jdn - JD_OFFSET) / 146097)
               + 100 * Math.floor(r400 / 36524)
               + 4 * Math.floor(r100 / 1461)
               + Math.floor(r4 / 365)
               - Math.floor(r4 / 1460)
               - Math.floor(r2000 / 730484);
  const year = aprime + 1;
  const t = Math.floor((364 + s - n) / 306);
  let month = t * (Math.floor(n / 31) + 1) + (1 - t) * (Math.floor((5 * (n - s) + 13) / 153) + 1);
  n += 1 - Math.floor(r2000 / 730484);
  let day = n;

  if ((r100 === 0) && (n === 0) && (r400 !== 0)) {
    month = 12;
    day = 31;
  } else {
    monthDays[2] = (leapYear(year)) ? 29 : 28;
    for (let i = 1; i <= nMonths; i += 1) {
      if (n <= monthDays[i]) {
        day = n;
        break;
      }

      n -= monthDays[i];
    }
  }

  return { year, month, day };
}
521178
def date(self):
        ''' 
        '''
        utcnow = datetime.utcnow()
        return (utcnow + timedelta(hours=self.time_zone)).date()
902906
def get_month_start_date(self):
        """"""
        now = timezone.now()
        return timezone.datetime(day=1, month=now.month, year=now.year, tzinfo=now.tzinfo)
462184
def get_upcoming_event_lists_for_the_remainder_of_the_month(self, year = None, month = None):
        ''''''

        events = []
        if year == None and month == None:
            now = datetime.now(tz=self.timezone) # timezone?
        else:
            now = datetime(year=year, month=month, day=1, hour=0, minute=0, second=0, tzinfo=self.timezone)

        # Get today's events, including past events
        start_time = datetime(year=now.year, month=now.month, day=now.day, hour=0, minute=0, second=0, tzinfo=self.timezone)
        end_time = datetime(year = start_time.year, month = start_time.month, day = start_time.day, hour=23, minute=59, second=59, tzinfo=self.timezone)
        events.append(self.get_events(start_time.isoformat(), end_time.isoformat()))

        # Get this week's events
        if now.weekday() < 6:
            start_time = datetime(year=now.year, month=now.month, day=now.day + 1, hour=0, minute=0, second=0, tzinfo=self.timezone)
            end_time = start_time + timedelta(days = 6 - now.weekday())
            # We do still want to return events in the next month if they fall within this week. Otherwise
            #if end_time.month != now.month:
            #    end_time = end_time - timedelta(days = end_time.day)
            #    end_time = datetime(year = end_time.year, month = end_time.month, day = end_time.day, hour=23, minute=59, second=59, tzinfo=self.timezone)
            #else:
            end_time = end_time + timedelta(seconds = -1)
            #end_time = datetime(year = end_time.year, month = end_time.month, day = end_time.day - 1, hour=23, minute=59, second=59, tzinfo=self.timezone)
            events.append(self.get_events(start_time.isoformat(), end_time.isoformat()))
        else:
            events.append([])

        # Get this remaining events in the month
        start_time = end_time + timedelta(seconds = 1)
        if start_time.month == now.month:
            if now.month == 12:
                end_time = datetime(year = start_time.year, month = 12, day = 31, hour=23, minute=59, second=59, tzinfo=self.timezone)
            else:
                end_time = datetime(year = start_time.year, month = start_time.month + 1, day = 1, hour=0, minute=0, second=0, tzinfo=self.timezone)
                end_time = end_time - timedelta(seconds = 1)
            events.append(self.get_events(start_time.isoformat(), end_time.isoformat()))
        else:
            events.append([])

        return events
1349642
def nexttime(self, lastts):
        '''
        
        '''
        lastdt = datetime.datetime.fromtimestamp(lastts, tz.utc)
        newvals = {}  # all the new fields that will be changed in datetime of lastts

        # Truncate the seconds part
        newdt = lastdt.replace(second=0)

        for unit, newval in self.reqdict.items():
            dtkey = _TimeunitToDatetime[unit]
            if unit is TimeUnit.DAYOFWEEK:
                newdt = newdt.replace(**newvals)
                newvals = {}
                newval = newdt.day + (6 + newval - newdt.weekday()) % 7 + 1
                if newval > calendar.monthrange(newdt.year, newdt.month)[1]:
                    newval -= 7
            elif unit is TimeUnit.MONTH:
                # As we change the month, clamp the day of the month to a valid value
                newdt = newdt.replace(**newvals)
                newvals = {}
                dayval = _dayofmonth(newdt.day, newval, newdt.year)
                newvals['day'] = dayval
            elif unit is TimeUnit.DAYOFMONTH:
                newdt = newdt.replace(**newvals)
                newvals = {}
                newval = _dayofmonth(newval, newdt.month, newdt.year)

            newvals[dtkey] = newval

        newdt = newdt.replace(**newvals)

        # Then move forward if we have to
        if newdt <= lastdt or \
                self.incunit == TimeUnit.DAYOFWEEK and newdt.weekday() != self.incval:
            if self.incunit is None:
                largest_req = min(self.reqdict.keys())
                tmpunit = _NextUnitMap[largest_req]
                if tmpunit is None:  # required a year and we're already there
                    return 0.0
                # Unless we're going to the next day of week, increment by 1 unit of the next larger unit
                tmpincval = self.reqdict.get(TimeUnit.DAYOFWEEK, 1)
            else:
                tmpunit = self.incunit
                tmpincval = self.incval
            newdt = self._inc(tmpunit, tmpincval, self.reqdict, lastdt, newdt)
            assert newdt > lastdt
        return newdt.timestamp()
1203244
def prevSolarReturn(date, lon):
    
    jd = eph.prevSolarReturn(date.jd, lon)
    return Datetime.fromJD(jd, date.utcoffset)
188356
def check_in_bounds(self, date):
        '''
        '''
        dt = Timestamp(date)
        return ((self._lbound is None or dt >= self._lbound) and
                (self._rbound is None or dt <= self._rbound))
890083
def _prev_month(self):
        """"""
        self._canvas.place_forget()

        self._date = self._date - self.timedelta(days=1)
        self._date = self.datetime(self._date.year, self._date.month, 1)
        self._build_calendar()
520581
def datetimes(self):
        """"""
        if self._timestamps_data is None:
            self._calculate_timestamps()
        return tuple(DateTime.from_moy(moy, self.is_leap_year)
                     for moy in self._timestamps_data)
521599
def round_to(self, dt, hour, minute, second, mode="floor"):
        
        mode = mode.lower()

        new_dt = datetime(dt.year, dt.month, dt.day, hour, minute, second)
        if mode == "floor":
            if new_dt <= dt:
                return new_dt
            else:
                return rolex.add_days(new_dt, -1)
        elif mode == "ceiling":
            if new_dt >= dt:
                return new_dt
            else:
                return rolex.add_days(new_dt, 1)
        else:
            raise ValueError("'mode' has to be 'floor' or 'ceiling'!")
1023810
function getFuzzyLocalTimeFromPoint(timestamp, point) {
  var tile = tilebelt.pointToTile(point[0], point[1], z).join('/');
  var locale = tiles[tile];

  if (locale) return moment.tz(new Date(timestamp), locale);
  else return undefined;
}
698750
def closest(self, dt1, dt2):
        
        dt1 = self.__class__(dt1.year, dt1.month, dt1.day)
        dt2 = self.__class__(dt2.year, dt2.month, dt2.day)

        if self.diff(dt1).in_seconds() < self.diff(dt2).in_seconds():
            return dt1

        return dt2
755681
def this_month(today: datetime=None, tz=None):
    
    if today is None:
        today = datetime.utcnow()
    begin = datetime(day=1, month=today.month, year=today.year)
    end = begin + timedelta(days=32)
    end = datetime(day=1, month=end.month, year=end.year)
    return localize_time_range(begin, end, tz)