Python datetime.date.month() Examples

The following are 30 code examples of datetime.date.month(). 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.date , or try the search function .
Example #1
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        n = self.n
        other = datetime(other.year, other.month, other.day,
                         other.hour, other.minute, other.second,
                         other.microsecond)
        wkday, days_in_month = tslib.monthrange(other.year, other.month)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= days_in_month and monthsToGo == 0):
            n = n - 1

        other = other + relativedelta(months=monthsToGo + 3 * n, day=31)
        return other 
Example #2
Source File: offsets.py    From Computable with MIT License 6 votes vote down vote up
def apply(self, other):
        n = self.n

        wkday, _ = tslib.monthrange(other.year, other.month)
        first = _get_firstbday(wkday)

        if other.day > first and n <= 0:
            # as if rolled forward already
            n += 1
        elif other.day < first and n > 0:
            other = as_datetime(other) + timedelta(days=first - other.day)
            n -= 1

        other = as_datetime(other) + relativedelta(months=n)
        wkday, _ = tslib.monthrange(other.year, other.month)
        first = _get_firstbday(wkday)
        result = datetime(other.year, other.month, first)
        return as_timestamp(result) 
Example #3
Source File: offsets.py    From Computable with MIT License 6 votes vote down vote up
def apply(self, other):
        n = self.n

        wkday, days_in_month = tslib.monthrange(other.year, other.month)
        lastBDay = days_in_month - max(((wkday + days_in_month - 1)
                                        % 7) - 4, 0)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= lastBDay and monthsToGo == 0):
            n = n - 1
        elif n <= 0 and other.day > lastBDay and monthsToGo == 0:
            n = n + 1

        other = as_datetime(other) + relativedelta(months=monthsToGo + 3 * n, day=31)

        if other.weekday() > 4:
            other = other - BDay()

        return other 
Example #4
Source File: offsets.py    From Computable with MIT License 6 votes vote down vote up
def apply(self, other):
        n = self.n
        other = as_datetime(other)

        wkday, days_in_month = tslib.monthrange(other.year, other.month)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= days_in_month and monthsToGo == 0):
            n = n - 1

        other = other + relativedelta(months=monthsToGo + 3 * n, day=31)

        return as_timestamp(other) 
Example #5
Source File: offsets.py    From Computable with MIT License 6 votes vote down vote up
def apply(self, other):
        n = self.n
        other = as_datetime(other)

        wkday, days_in_month = tslib.monthrange(other.year, other.month)

        monthsSince = (other.month - self.startingMonth) % 3

        if n <= 0 and monthsSince != 0:
            # make sure you roll forward, so negate
            monthsSince = monthsSince - 3

        if n < 0 and (monthsSince == 0 and other.day > 1):
            # after start, so come back an extra period as if rolled forward
            n = n + 1

        other = other + relativedelta(months=3 * n - monthsSince, day=1)
        return as_timestamp(other) 
Example #6
Source File: offsets.py    From Computable with MIT License 6 votes vote down vote up
def apply(self, other):
        n = self.n
        other = as_datetime(other)

        wkday, days_in_month = tslib.monthrange(other.year, self.month)

        first = _get_firstbday(wkday)

        years = n

        if n > 0:  # roll back first for positive n
            if (other.month < self.month or
                    (other.month == self.month and other.day < first)):
                years -= 1
        elif n <= 0:  # roll forward
            if (other.month > self.month or
                    (other.month == self.month and other.day > first)):
                years += 1

        # set first bday for result
        other = other + relativedelta(years=years)
        wkday, days_in_month = tslib.monthrange(other.year, self.month)
        first = _get_firstbday(wkday)
        return as_timestamp(datetime(other.year, self.month, first)) 
Example #7
Source File: ranbyus.py    From dga-collection with MIT License 6 votes vote down vote up
def dga(date, seed, nr):
  tlds = ['.in', '.me', '.cc', '.su', '.tw', '.net', '.com', '.pw', '.org']
  tld_index = date.day
  day = date.day
  month = date.month
  year = date.year
  uint_mask = 0xFFFFFFFF
  for d in range(nr):
    domain = ''
    for i in range(14):
      day = (day >> 15) ^ 16 * (day & 0x1FFF ^ 4 * (seed ^ day))
      day &= uint_mask
      year_times7 = 7 * year & uint_mask
      year = (((year & 0xFFFFFFF0) << 17) & uint_mask) ^ ((year ^ year_times7) >> 11)
      month_times4 = 4 * month & uint_mask
      month = (14 * (month & 0xFFFFFFFE) & uint_mask) ^ ((month ^ month_times4) >> 8)
      seed_times8 = 8 * seed & uint_mask
      seed = (seed >> 6) ^ ((day + seed_times8 << 8) & uint_mask) & 0x3FFFF00
      x = ((day ^ month ^ year) % 25) + 97
      domain += chr(x)
    print(domain + tlds[tld_index % 8])
    tld_index += 1 
Example #8
Source File: dt.py    From ladybug with GNU General Public License v3.0 6 votes vote down vote up
def from_date_time_string(cls, datetime_string, leap_year=False):
        """Create Ladybug DateTime from a DateTime string.

        Args:
            datetime_string: A text string representing a DateTime
                (ie. "21 Jun 12:00")
            leap_year: Boolean to note whether the Date Time is a part of a
                leap year. Default: False.

        Usage:

        .. code-block:: python

            dt = DateTime.from_date_time_string("31 Dec 12:00")
        """
        try:
            dt = datetime.strptime(datetime_string, '%d %b %H:%M')
        except AttributeError:  # older Python version before strptime
            vals = datetime_string.split(' ')
            tim = vals[-1].split(':')
            dt = datetime(2016, MONTHNAMES.index(vals[1]) + 1, int(vals[0]),
                          int(tim[0]), int(tim[1]))
        return cls(dt.month, dt.day, dt.hour, dt.minute, leap_year) 
Example #9
Source File: dt.py    From ladybug with GNU General Public License v3.0 6 votes vote down vote up
def from_dict(cls, data):
        """Create date from a dictionary.

        Args:
            data: A python dictionary in the following format

        .. code-block:: python

                {
                'month': 1  # A value for month between 1-12. (Default: 1)
                'day': 1  # A value for day between 1-31. (Default: 1)
                }
        """
        month = data['month'] if 'month' in data else 1
        day = data['day'] if 'day' in data else 1
        leap_year = data['leap_year'] if 'leap_year' in data else False
        return cls(month, day, leap_year) 
Example #10
Source File: dt.py    From ladybug with GNU General Public License v3.0 6 votes vote down vote up
def from_dict(cls, data):
        """Create time from a dictionary.

        Args:
            data: A python dictionary in the following format

        .. code-block:: python

                {
                'hour': 0  # A value for hour between 0-23. (Default: 0)
                'minute': 0  # A value for month between 0-59. (Default: 0)
                }
        """
        hour = data['hour'] if 'hour' in data else 0
        minute = data['minute'] if 'minute' in data else 0
        return cls(hour, minute) 
Example #11
Source File: dateentry.py    From amir with GNU General Public License v3.0 6 votes vote down vote up
def dateToString(date):
    if share.config.datetypes[share.config.datetype] == "jalali":
        jd = DateEntry.cal.gregorian_to_jd(date.year, date.month, date.day)
        (year, month, day) = DateEntry.cal.jd_to_jalali(jd)
    else:
        (year, month, day) = (date.year, date.month, date.day)

    datelist = ["", "", ""]
    datelist[share.config.datefields["year"]] = year
    datelist[share.config.datefields["month"]] = month
    datelist[share.config.datefields["day"]] = day

    delim = share.config.datedelims[share.config.datedelim]
    datestring = str(datelist[0]) + delim + \
        str(datelist[1]) + delim + str(datelist[2])
    datestring = LN(datestring, False)
    return datestring 
Example #12
Source File: dateentry.py    From amir with GNU General Public License v3.0 6 votes vote down vote up
def showDate(self, year, month, day):
        datelist = ["", "", ""]
        datelist[share.config.datefields["year"]] = year
        datelist[share.config.datefields["month"]] = month
        datelist[share.config.datefields["day"]] = day

        delim = share.config.datedelims[share.config.datedelim]
        datestring = str(datelist[0]) + delim + \
            str(datelist[1]) + delim + str(datelist[2])
        datestring = LN(datestring, False)
        self.set_text(datestring)
        self.year = year
        self.month = month
        self.day = day

    # Assuming that date objects show gregorian date. 
Example #13
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _next_opening_time(self, other):
        """
        If n is positive, return tomorrow's business day opening time.
        Otherwise yesterday's business day's opening time.

        Opening time always locates on BusinessDay.
        Otherwise, closing time may not if business hour extends over midnight.
        """
        if not self.next_bday.onOffset(other):
            other = other + self.next_bday
        else:
            if self.n >= 0 and self.start < other.time():
                other = other + self.next_bday
            elif self.n < 0 and other.time() < self.start:
                other = other + self.next_bday
        return datetime(other.year, other.month, other.day,
                        self.start.hour, self.start.minute) 
Example #14
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        n = self.n
        if not self.onOffset(other):
            _, days_in_month = tslib.monthrange(other.year, other.month)
            if 1 < other.day < self.day_of_month:
                other += relativedelta(day=self.day_of_month)
                if n > 0:
                    # rollforward so subtract 1
                    n -= 1
            elif self.day_of_month < other.day < days_in_month:
                other += relativedelta(day=self.day_of_month)
                if n < 0:
                    # rollforward in the negative direction so add 1
                    n += 1
                elif n == 0:
                    n = 1

        return self._apply(n, other) 
Example #15
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply_index(self, i):
        # determine how many days away from the 1st of the month we are
        days_from_start = i.to_perioddelta('M').asi8
        delta = Timedelta(days=self.day_of_month - 1).value

        # get boolean array for each element before the day_of_month
        before_day_of_month = days_from_start < delta

        # get boolean array for each element after the day_of_month
        after_day_of_month = days_from_start > delta

        # determine the correct n for each date in i
        roll = self._get_roll(i, before_day_of_month, after_day_of_month)

        # isolate the time since it will be striped away one the next line
        time = i.to_perioddelta('D')

        # apply the correct number of months
        i = (i.to_period('M') + (roll // 2)).to_timestamp()

        # apply the correct day
        i = self._apply_index_days(i, roll)

        return i + time 
Example #16
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        n = self.n
        # First move to month offset
        cur_mend = self.m_offset.rollforward(other)
        # Find this custom month offset
        cur_cmend = self.cbday.rollback(cur_mend)

        # handle zero case. arbitrarily rollforward
        if n == 0 and other != cur_cmend:
            n += 1

        if other < cur_cmend and n >= 1:
            n -= 1
        elif other > cur_cmend and n <= -1:
            n += 1

        new = cur_mend + n * self.m_offset
        result = self.cbday.rollback(new)
        return result 
Example #17
Source File: dateentry.py    From amir with GNU General Public License v3.0 6 votes vote down vote up
def stringToDate(dateString):
    dateString = convertToLatin(dateString)
    delim = share.config.datedelims[share.config.datedelim]
    dateList = dateString.split(delim)
    if len(dateList) == 3:
        if dateList[0] != '' and dateList[1] != '' and dateList[2] != '':
            dy = int(dateList[share.config.datefields["year"]])
            dm = int(dateList[share.config.datefields["month"]])
            dd = int(dateList[share.config.datefields["day"]])
            d = (dy, dm, dd)
            de = DateEntry(d)
            try:
                dateObj = de.getDateObject()
            except:
                return
            return dateObj
## @}

## \defgroup Widgets
## @{ 
Example #18
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        n = self.n
        dt_in = other
        # First move to month offset
        cur_mbegin = self.m_offset.rollback(dt_in)
        # Find this custom month offset
        cur_cmbegin = self.cbday.rollforward(cur_mbegin)

        # handle zero case. arbitrarily rollforward
        if n == 0 and dt_in != cur_cmbegin:
            n += 1

        if dt_in > cur_cmbegin and n <= -1:
            n += 1
        elif dt_in < cur_cmbegin and n >= 1:
            n -= 1

        new = cur_mbegin + n * self.m_offset
        result = self.cbday.rollforward(new)
        return result 
Example #19
Source File: dt.py    From ladybug with GNU General Public License v3.0 6 votes vote down vote up
def from_dict(cls, data):
        """Create datetime from a dictionary.

        Args:
            data: A python dictionary in the following format

        .. code-block:: python

                {
                'month': 1  #A value for month between 1-12. (Default: 1)
                'day': 1  # A value for day between 1-31. (Default: 1)
                'hour': 0  # A value for hour between 0-23. (Default: 0)
                'minute': 0  # A value for month between 0-59. (Default: 0)
                }
        """
        month = data['month'] if 'month' in data else 1
        day = data['day'] if 'day' in data else 1
        hour = data['hour'] if 'hour' in data else 0
        minute = data['minute'] if 'minute' in data else 0
        leap_year = data['leap_year'] if 'leap_year' in data else False
        return cls(month, day, hour, minute, leap_year) 
Example #20
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        base = other
        if self.weekday is None:
            return other + self.n * self._inc

        if self.n > 0:
            k = self.n
            otherDay = other.weekday()
            if otherDay != self.weekday:
                other = other + timedelta((self.weekday - otherDay) % 7)
                k = k - 1
            for i in range(k):
                other = other + self._inc
        else:
            k = self.n
            otherDay = other.weekday()
            if otherDay != self.weekday:
                other = other + timedelta((self.weekday - otherDay) % 7)
            for i in range(-k):
                other = other - self._inc

        other = datetime(other.year, other.month, other.day,
                         base.hour, base.minute, base.second, base.microsecond)
        return other 
Example #21
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        n = self.n
        base = other
        other = datetime(other.year, other.month, other.day,
                         other.hour, other.minute, other.second,
                         other.microsecond)

        wkday, days_in_month = tslib.monthrange(other.year, other.month)
        lastBDay = days_in_month - max(((wkday + days_in_month - 1)
                                        % 7) - 4, 0)

        monthsToGo = 3 - ((other.month - self.startingMonth) % 3)
        if monthsToGo == 3:
            monthsToGo = 0

        if n > 0 and not (other.day >= lastBDay and monthsToGo == 0):
            n = n - 1
        elif n <= 0 and other.day > lastBDay and monthsToGo == 0:
            n = n + 1

        other = other + relativedelta(months=monthsToGo + 3 * n, day=31)
        other = tslib._localize_pydatetime(other, base.tzinfo)
        if other.weekday() > 4:
            other = other - BDay()
        return other 
Example #22
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def apply(self, other):
        base = other
        offsetOfMonth = self.getOffsetOfMonth(other)

        if offsetOfMonth > other:
            if self.n > 0:
                months = self.n - 1
            else:
                months = self.n
        elif offsetOfMonth == other:
            months = self.n
        else:
            if self.n > 0:
                months = self.n
            else:
                months = self.n + 1

        other = self.getOffsetOfMonth(
            other + relativedelta(months=months, day=1))
        other = datetime(other.year, other.month, other.day, base.hour,
                         base.minute, base.second, base.microsecond)
        return other 
Example #23
Source File: dt.py    From ladybug with GNU General Public License v3.0 5 votes vote down vote up
def from_date_string(cls, date_string, leap_year=False):
        """Create Ladybug Date from a Date string.

        Usage:

        .. code-block:: python

            dt = Date.from_date_string("31 Dec")
        """
        try:
            dt = datetime.strptime(date_string, '%d %b')
        except AttributeError:  # older Python version before strptime
            vals = date_string.split(' ')
            dt = datetime(2016, MONTHNAMES.index(vals[1]) + 1, int(vals[0]))
        return cls(dt.month, dt.day, leap_year) 
Example #24
Source File: dt.py    From ladybug with GNU General Public License v3.0 5 votes vote down vote up
def to_array(self):
        """Return date as an array of values."""
        if not self.leap_year:
            return (self.month, self.day)
        return (self.month, self.day, 1) 
Example #25
Source File: dateentry.py    From amir with GNU General Public License v3.0 5 votes vote down vote up
def showDateObject(self, date):
        if share.config.datetypes[share.config.datetype] == "jalali":
            jd = self.cal.gregorian_to_jd(date.year, date.month, date.day)
            (jyear, jmonth, jday) = self.cal.jd_to_jalali(jd)
            self.showDate(jyear, jmonth, jday)
        else:
            self.showDate(date.year, date.month, date.day) 
Example #26
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _prev_opening_time(self, other):
        """
        If n is positive, return yesterday's business day opening time.
        Otherwise yesterday business day's opening time.
        """
        if not self.next_bday.onOffset(other):
            other = other - self.next_bday
        else:
            if self.n >= 0 and other.time() < self.start:
                other = other - self.next_bday
            elif self.n < 0 and other.time() > self.start:
                other = other - self.next_bday
        return datetime(other.year, other.month, other.day,
                        self.start.hour, self.start.minute) 
Example #27
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def onOffset(self, dt):
        if self.normalize and not _is_normalized(dt):
            return False

        if dt.tzinfo is not None:
            dt = datetime(dt.year, dt.month, dt.day, dt.hour,
                          dt.minute, dt.second, dt.microsecond)
        # Valid BH can be on the different BusinessDay during midnight
        # Distinguish by the time spent from previous opening time
        businesshours = self._get_business_hours_by_sec()
        return self._onOffset(dt, businesshours) 
Example #28
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def name(self):
        if self.isAnchored:
            return self.rule_code
        else:
            return "{code}-{month}".format(code=self.rule_code,
                                           month=_int_to_month[self.n]) 
Example #29
Source File: offsets.py    From Computable with MIT License 5 votes vote down vote up
def getOffsetOfMonth(self, dt):
        m =  MonthEnd()
        d = datetime(dt.year, dt.month, 1)

        eom = m.rollforward(d)

        w = Week(weekday=self.weekday)

        return w.rollback(eom) 
Example #30
Source File: offsets.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def apply(self, other):
        n = self.n
        _, days_in_month = tslib.monthrange(other.year, other.month)
        if other.day != days_in_month:
            other = other + relativedelta(months=-1, day=31)
            if n <= 0:
                n = n + 1
        other = other + relativedelta(months=n, day=31)
        return other