コード例 #1
0
def test_convert_from_pandas(pd):
    pf = pd.DataFrame(
        {"A": pd.to_datetime(['2000-01-01 01:01:01', '2010-11-07 23:04:11'])})
    DT = dt.Frame(pf)
    assert_equals(
        DT, dt.Frame(A=[d(2000, 1, 1, 1, 1, 1),
                        d(2010, 11, 7, 23, 4, 11)]))
コード例 #2
0
    def test_in_range(self):
        now = d(year=2020, month=3, day=15)

        def _assert_in_range(start: Optional[datetime.date],
                             end: Optional[datetime.date]):
            self.assertTrue(timeutil.in_range(now, start, end))

        def _assert_not_in_range(start: Optional[datetime.date],
                                 end: Optional[datetime.date]):
            self.assertFalse(timeutil.in_range(now, start, end))

        _assert_in_range(None, None)
        _assert_in_range(None, d(2021, 3, 15))

        _assert_in_range(d(2001, 4, 16), d(2032, 1, 24))

        _assert_not_in_range(now, now)
        _assert_in_range(now, None)
        _assert_not_in_range(None, now)

        _assert_not_in_range(d(2032, 1, 24), None)
        _assert_not_in_range(None, d(2001, 4, 16))

        _assert_not_in_range(d(2001, 4, 16), d(2003, 5, 17))
        _assert_not_in_range(d(2032, 1, 24), d(2078, 1, 12))
コード例 #3
0
def meetup_day(year, month, day, week):
    week_dict = {
        '1st': (1, 8),
        '2nd': (8, 15),
        '3rd': (15, 22),
        '4th': (21, 29),
        'teenth': (13, 20)
    }
    weekday = {
        'Monday': 0,
        'Tuesday': 1,
        'Wednesday': 2,
        'Thursday': 3,
        'Friday': 4,
        'Saturday': 5,
        'Sunday': 6
    }
    if week == 'last':
        last_day = calendar.monthrange(year, month)[1]
        for num in range(last_day, last_day - 7, -1):
            if d(year, month, num).weekday() == weekday[day]:
                return d(year, month, num)
    else:
        for num in range(week_dict[week][0], week_dict[week][1]):
            if d(year, month, num).weekday() == weekday[day]:
                return d(year, month, num)
コード例 #4
0
    def test_years_between(self):
        self.assertEqual(
            timeutil.years_between(d(year=2000, month=1, day=1),
                                   d(year=2001, month=1, day=1)),
            1,
        )
        self.assertEqual(
            timeutil.years_between(d(year=2000, month=1, day=1),
                                   d(year=2000, month=12, day=31)),
            0,
        )
        self.assertEqual(
            timeutil.years_between(d(year=2000, month=1, day=1),
                                   d(year=2001, month=12, day=31)),
            1,
        )
        self.assertEqual(
            timeutil.years_between(d(year=2000, month=1, day=1),
                                   d(year=2005, month=4, day=16)),
            5,
        )

        # If dates are in wrong order return 0, not a negative number or normalised positive.
        self.assertEqual(
            timeutil.years_between(d(year=2005, month=4, day=16),
                                   d(year=2000, month=1, day=1)),
            0,
        )
コード例 #5
0
ファイル: test-date32.py プロジェクト: dmillar/datatable
def test_date32_create_from_string_list():
    DT = dt.Frame(['1901-04-11', '1969-12-31', 'NaT', '2000-10-07', '2015-11-21'],
                  type=dt.Type.date32)
    assert DT.type == dt.Type.date32
    assert DT.to_list() == [
        [d(1901, 4, 11), d(1969, 12, 31), None, d(2000, 10, 7), d(2015, 11, 21)]
    ]
コード例 #6
0
def test_date32_iso():
    from datetime import date as d
    DT = dt.fread("A\n2000-01-01\n2010-11-11\n2020-12-31\n")
    assert_equals(
        DT, dt.Frame(
            A=[d(2000, 1, 1), d(2010, 11, 11),
               d(2020, 12, 31)]))
コード例 #7
0
def test_cast_date32_to_obj():
    from datetime import date as d
    src = [d(2000, 1, 5), d(2001, 6, 2), None, d(831, 11, 11)]
    DT = dt.Frame(A=src)
    assert DT.types == [dt.Type.date32]
    DT['A'] = object
    assert_equals(DT, dt.Frame(A=src, stype=dt.obj64))
コード例 #8
0
def focus(startH, startM, endH, endM):
    while True:
        # time of your work
        if (d(d.now().year,
              d.now().month,
              d.now().day, startH, startM) < d.now() < d(
                  d.now().year,
                  d.now().month,
                  d.now().day, endH, endM)):
            print("Working hour...", d.now())
            with open(hosts_path, "r+") as file:
                content = file.read()
                for website in websites:
                    if website in content:
                        pass
                    else:
                        # mapping hostnames to your localhost IP address
                        file.write(redirect + " " + website + "\n")
            for application in applications:
                if application in (p.name() for p in psutil.process_iter()):
                    os.system("taskkill /im " +
                              application)  # select process by its name
        else:
            with open(hosts_path, "r+") as file:
                content = file.readlines()
                file.seek(0)
                for line in content:
                    if not any(website in line for website in websites):
                        file.write(line)
                # removing hostnmes from host file
                file.truncate()
            print("Chill time", d.now())

        time.sleep(2)
コード例 #9
0
 def test_set(self):
     from datetime import date
     date.set(2001, 1, 2)
     compare(date.today(), d(2001, 1, 2))
     date.set(2002, 1, 1)
     compare(date.today(), d(2002, 1, 1))
     compare(date.today(), d(2002, 1, 3))
コード例 #10
0
 def test_set(self):
     from datetime import datetime
     datetime.set(2001, 1, 1, 1, 0, 1)
     compare(datetime.now(), d(2001, 1, 1, 1, 0, 1))
     datetime.set(2002, 1, 1, 1, 0, 0)
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 20))
コード例 #11
0
    def test_isinstance_default(self):
        from datetime import date
        to_check = []
        to_check.append(date(1999, 1, 1))
        to_check.append(date.today())
        date.set(2001, 1, 2)
        to_check.append(date.today())
        date.add(2001, 1, 3)
        to_check.append(date.today())
        to_check.append(date.today())
        date.set(date(2001, 1, 4))
        to_check.append(date.today())
        date.add(date(2001, 1, 5))
        to_check.append(date.today())
        to_check.append(date.today())
        date.set(d(2001, 1, 4))
        to_check.append(date.today())
        date.add(d(2001, 1, 5))
        to_check.append(date.today())
        to_check.append(date.today())

        for inst in to_check:
            self.failIf(isinstance(inst, date), inst)
            self.failIf(inst.__class__ is date, inst)
            self.failUnless(isinstance(inst, d), inst)
            self.failUnless(inst.__class__ is d, inst)
コード例 #12
0
ファイル: test-date32.py プロジェクト: dmillar/datatable
def test_cast_object_to_date32():
    DT = dt.Frame([d(2001, 1, 1), d(2021, 10, 15), 3.14159, None, list],
                  type=object)
    DT[0] = dt.Type.date32
    assert_equals(DT, dt.Frame([d(2001, 1, 1),
                                d(2021, 10, 15),
                                None, None, None]))
コード例 #13
0
    def countdown(self):

        # format = str(dt.now())

        # format = ""
        # # format += "weKILLpedia "
        # format += "<span color='#0000FF'>weKILLpedia "
        # format += str((d.today()-d(2019,4,23)).days+1) + "</span>"
        # format += "  <span color='#222222'>AntiELAB "
        # format += str((d.today()-d(2019,6,9)).days+1) + "</span>"
        # format += "  <span color='#FF0000'>Final "
        # format += str((d(2020,1,5)-d.today()).days) + "</span>"

        format = ""
        # format += "<span color='#00FF00'>"
        # format += str((d.today()-d()).days+1)
        # format += "</span>  "
        format += "weKILLpedia "
        format += str((d.today() - d(2019, 4, 23)).days + 1)
        format += "  AntiELAB "
        format += str((d.today() - d(2019, 6, 9)).days + 1)
        format += "  Coronavirus "
        format += str((d.today() - d(2019, 12, 1)).days + 1)

        return {
            # 'full_text': self.format,
            # 'cached_until': self.py3.CACHE_FOREVER
            'full_text': format,
            "cached_until": self.py3.time_in(self.cache_timeout)
        }
コード例 #14
0
ファイル: test-date32.py プロジェクト: dmillar/datatable
def test_date32_to_arrow(pa):
    DT = dt.Frame([17, 349837, 88888, None, 17777], stype='date32')
    tbl = DT.to_arrow()
    assert isinstance(tbl, pa.Table)
    assert tbl.to_pydict() == {"C0": [
        d(1970, 1, 18), d(2927, 10, 28), d(2213, 5, 15), None, d(2018, 9, 3)
    ]}
コード例 #15
0
    def test_isinstance_default(self):
        from datetime import datetime
        to_check = []
        to_check.append(datetime(1999, 1, 1))
        to_check.append(datetime.now())
        to_check.append(datetime.now(TestTZInfo()))
        to_check.append(datetime.utcnow())
        datetime.set(2001, 1, 1, 20)
        to_check.append(datetime.now())
        datetime.add(2001, 1, 1, 21)
        to_check.append(datetime.now())
        to_check.append(datetime.now(TestTZInfo()))
        datetime.set(datetime(2001, 1, 1, 22))
        to_check.append(datetime.now())
        datetime.add(datetime(2001, 1, 1, 23))
        to_check.append(datetime.now())
        to_check.append(datetime.now())
        to_check.append(datetime.now(TestTZInfo()))
        datetime.set(d(2001, 1, 1, 22))
        to_check.append(datetime.now())
        datetime.add(d(2001, 1, 1, 23))
        to_check.append(datetime.now())
        to_check.append(datetime.now())
        to_check.append(datetime.now(TestTZInfo()))

        for inst in to_check:
            self.failIf(isinstance(inst, datetime), inst)
            self.failIf(inst.__class__ is datetime, inst)
            self.failUnless(isinstance(inst, d), inst)
            self.failUnless(inst.__class__ is d, inst)
コード例 #16
0
 def test_today_sequence(self, t):
     t.add(2002, 1, 1)
     t.add(2002, 1, 2)
     t.add(2002, 1, 3)
     from datetime import date
     compare(date.today(), d(2002, 1, 1))
     compare(date.today(), d(2002, 1, 2))
     compare(date.today(), d(2002, 1, 3))
コード例 #17
0
ファイル: test-to-numpy.py プロジェクト: imvansh25/datatable
def test_tonumpy_date32_with_nas(np):
    from datetime import date as d
    DT = dt.Frame([d(1990, 5, 28), d(980, 3, 1), None, d(2096, 11, 30)])
    assert DT.types[0] == dt.Type.date32
    a = DT.to_numpy()
    assert a.dtype == np.dtype('datetime64[D]')
    assert a.shape == DT.shape
    assert a.T.tolist() == DT.to_list()
コード例 #18
0
ファイル: test-to-numpy.py プロジェクト: imvansh25/datatable
def test_tonumpy_date32(np):
    from datetime import date as d
    DT = dt.Frame([d(2001, 1, 1), d(2002, 3, 5), d(2012, 2, 7), d(2020, 3, 9)])
    assert DT.types[0] == dt.Type.date32
    a = DT.to_numpy()
    assert a.dtype == np.dtype('datetime64[D]')
    assert a.shape == DT.shape
    assert a.T.tolist() == DT.to_list()
コード例 #19
0
 def test_add_datetime_supplied(self, t):
     from datetime import datetime
     t.add(d(2002, 1, 1, 1))
     t.add(datetime(2002, 1, 1, 2))
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 0))
     with ShouldRaise(ValueError('Cannot add datetime with tzinfo set')):
         t.add(d(2001, 1, 1, tzinfo=TestTZInfo()))
コード例 #20
0
def test_materialize():
    DT = dt.Frame([d(2021, 4, 1, i, 0, 0) for i in range(24)])
    assert DT.type == dt.Type.time64
    RES = DT[::2, :]
    EXP = dt.Frame([d(2021, 4, 1, i, 0, 0) for i in range(24)[::2]])
    assert_equals(RES, EXP)
    RES.materialize()
    assert_equals(RES, EXP)
コード例 #21
0
ファイル: test-date32.py プロジェクト: dmillar/datatable
def test_date32_mean():
    dd = datetime.datetime
    src = [None,
           d(2010, 11, 13),
           d(2010, 11, 14)]
    DT = dt.Frame(src)
    assert DT.mean1() ==  dd(2010, 11, 13, 12, 0, 0)
    assert_equals(DT.mean(), dt.Frame([dd(2010, 11, 13, 12, 0, 0)]))
コード例 #22
0
 def test_today_requested_longer_than_supplied(self, t):
     t.add(2002, 1, 1)
     t.add(2002, 1, 2)
     from datetime import date
     compare(date.today(), d(2002, 1, 1))
     compare(date.today(), d(2002, 1, 2))
     compare(date.today(), d(2002, 1, 3))
     compare(date.today(), d(2002, 1, 5))
コード例 #23
0
 def test_daily(self):
     r = (d(2012, 1, 1), d(2012, 1, 3))
     actual = list(reactive_dates.daily(r))
     expected = [
         d(2012, 1, 1),
         d(2012, 1, 2),
         d(2012, 1, 3)]
     self.assertEqual(actual, expected)
コード例 #24
0
def focusMode2(startH, startM, endH, endM):
    while True:
        if (d(d.now().year, d.now().month, d.now().day, startH, startM)
                < d.now()
                < d(d.now().year, d.now().month, d.now().day, endH, endM)):
            focusMode('on')
        elif d.now() > d(d.now().year, d.now().month, d.now().day, endH, endM):
            return
コード例 #25
0
def test_nas():
    DT = dt.Frame([d(2001, 5, 17), None, d(2021, 3, 15), None])
    RES = DT[:, {"year": year(f[0]), "month": month(f[0]), "day": day(f[0])}]
    assert_equals(
        RES,
        dt.Frame(year=[2001, None, 2021, None],
                 month=[5, None, 3, None],
                 day=[17, None, 15, None]))
コード例 #26
0
ファイル: test_datemap.py プロジェクト: fagan2888/cydatemap
 def test_delta_of(self):
     dm = DateMap.from_tuples([self.y2001, self.y2003, self.y2004])
     assert_raises(ValueError, dm.delta_of, d(2000, 12, 31))
     assert_equal(dm.delta_of(d(2001, 12, 31)).days, 364)
     assert_equal(dm.delta_of(d(2003, 12, 31)).days, 2 * 364 + 1)
     assert_equal(dm.delta_of(d(2004, 12, 31)).days,
                  3 * 364 + 3)  #2004 was a leap year
     assert_raises(ValueError, dm.delta_of, d(2005, 1, 2))
コード例 #27
0
 def test_add_and_set(self, t):
     t.add(2002, 1, 1, 1, 0, 0)
     t.add(2002, 1, 1, 2, 0, 0)
     t.set(2002, 1, 1, 3, 0, 0)
     from datetime import datetime
     compare(datetime.now(), d(2002, 1, 1, 3, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 3, 0, 10))
     compare(datetime.now(), d(2002, 1, 1, 3, 0, 30))
コード例 #28
0
def test_time64_create_from_mixed_list2():
    from datetime import date
    DT = dt.Frame([None, date(2001, 1, 1), d(1999, 12, 31, 8, 30, 50)])
    assert_equals(
        DT,
        dt.Frame([None,
                  d(2001, 1, 1, 0, 0, 0),
                  d(1999, 12, 31, 8, 30, 50)]))
コード例 #29
0
 def test_now_requested_longer_than_supplied(self, t):
     t.add(2002, 1, 1, 1, 0, 0)
     t.add(2002, 1, 1, 2, 0, 0)
     from datetime import datetime
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 10))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 30))
コード例 #30
0
 def test_now_sequence(self, t):
     t.add(2002, 1, 1, 1, 0, 0)
     t.add(2002, 1, 1, 2, 0, 0)
     t.add(2002, 1, 1, 3, 0, 0)
     from datetime import datetime
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 3, 0, 0))
コード例 #31
0
ファイル: days.py プロジェクト: gragtah/sentiment
def add_entry(table_name, date):
    """
    Adds an entry for the specified day/week/month/year.
    Includes date, comments, article urls, and article titles.
    :param date: the date to be added.
    :return: None
    """
    db = create_engine("sqlite:///db/app.db", echo=False)
    metadata = MetaData(db)
    days = Table(table_name, metadata, autoload=True)

    clear_mappers()

    mapper(day.Day, days)

    session = Session()

    comment_index = 0
    url_index = 2
    num_days = 1

    if table_name == "weeks":
        num_days = 7
        iso_date = date.isocalendar()
        date = iso_to_gregorian(iso_date[0],iso_date[1],7)

    elif table_name == "months":
        if date.month == 12: 
            date = d(date.year, 12, 31)
        else:
            date = d(date.year, date.month + 1, 1) - timedelta(days=1)
        num_days = (date - d(date.year, date.month, 1)).days + 1

    elif table_name == "years":
        date = d(date.year, 12, 31)
        if date > d.today():
            date = d.today()
        num_days = (date - d(date.year, 1, 1)).days + 1

    sentiment, top_comments, top_votes, titles = scraper.analyze(date, num_days)

    # date indicates the first day of the week, month, or year analyzed
    today = day.Day(date=date - timedelta(days=num_days-1),
                       sentiment=sentiment.polarity,
                       comment1=top_comments[1][comment_index],
                       comment1_url=top_comments[1][url_index],
                       comment1_title=titles[1],
                       comment2=top_comments[2][comment_index],
                       comment2_url=top_comments[2][url_index],
                       comment2_title=titles[2],
                       comment3=top_comments[3][comment_index],
                       comment3_url=top_comments[3][url_index],
                       comment3_title=titles[3],
                       )
    session.add(today)
    session.commit()
    session.flush()
コード例 #32
0
 def test_add_datetime_supplied(self, t):
     from datetime import datetime
     t.add(d(2002, 1, 1, 1))
     t.add(datetime(2002, 1, 1, 2))
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 0))
     with ShouldRaise(ValueError(
         'Cannot add datetime with tzinfo set'
             )):
         t.add(d(2001, 1, 1, tzinfo=TestTZInfo()))
コード例 #33
0
ファイル: ValidId.py プロジェクト: Kallehz/Python
def valid(s):
    x = [3, 2, 7, 6, 5, 4, 3, 2]
    y = {'0': '20', '9' : '19'}
    t = -1

    try:
        d(int(y[s[9]]+ s[4:6]), int(s[2:4]), int(s[0:2]))
        t = (11 - (sum(map(m, x, [int(x) for x in list(s[:-2])])) % 11))

    finally:
        return t == int(s[8])
コード例 #34
0
 def test_set_datetime_supplied(self, t):
     from datetime import datetime
     t.set(d(2002, 1, 1, 1))
     compare(datetime.now(), d(2002, 1, 1, 1, 0, 0))
     t.set(datetime(2002, 1, 1, 2))
     compare(datetime.now(), d(2002, 1, 1, 2, 0, 0))
     tzinfo = SampleTZInfo()
     tzrepr = repr(tzinfo)
     with ShouldRaise(ValueError(
         'Cannot add datetime with tzinfo of %s as configured to use None' %(
             tzrepr
         ))):
         t.set(d(2001, 1, 1, tzinfo=tzinfo))
コード例 #35
0
ファイル: test_signal_cron.py プロジェクト: righ/bak
 def test_single_value(self):
     # 01-01 01:01 (sun)
     d1 = self._getTarget(1, 1, 1, 1, 0)
     # 01-01-01 01:01
     self.assertTrue(d1.evalute(None, now=d(1, 1, 1, 1, 1)))
     # 01-01-01 01:02
     self.assertFalse(d1.evalute(None, now=d(1, 1, 1, 1, 2)))
     # 01-01-01 02:01
     self.assertFalse(d1.evalute(None, now=d(1, 1, 1, 2, 1)))
     # 01-01-02 01:01
     self.assertFalse(d1.evalute(None, now=d(1, 1, 2, 1, 1)))
     # 01-02-01 01:01
     self.assertFalse(d1.evalute(None, now=d(1, 2, 1, 1, 1)))
コード例 #36
0
ファイル: weather.py プロジェクト: gragtah/sentiment
def main():

	weather_dict = {}
	month = d(2014,1,1)

	for i in range(1,13):
		weather_dict = get_month(weather_dict, d(month.year, i, 1))

	month = d(2015,1,1)

	for i in range(1,8):
		weather_dict = get_month(weather_dict, d(month.year, i, 1))

	pickle.dump(weather_dict, open("weather.p", "wb"))
コード例 #37
0
def test_date_ranges_arent_near(start, end, other_start, other_end):
    date = d(2000, 1, 5)
    obj = DateRange(dt.combine(date, start), dt.combine(date, end))
    other = DateRange(dt.combine(date, other_start), dt.combine(date, other_end))

    obj.near_time = td(seconds=300)
    assert not obj.near(other)
コード例 #38
0
ファイル: views.py プロジェクト: HiPiH/life
def post_detail(req, author, date, slug):
    reply_to = _get_reply_to(req)
    date = d(*time.strptime(date, '%Y-%m-%d')[:3])
    today = (dt.combine(date, t.min), dt.combine(date, t.max))
    post = get_object_or_404(Post.objects.filter(date__range=today), slug=slug, author__username=author)
    post.views_count = post.views_count + 1
    post.save()
    
    out = {}
    if req.user.username == author:
        out['validuser'] = req.user
        post.new_comments = False
        post.save()
    
    out.update({
            'post': post,
            'reply_to': reply_to,
            'site': Site.objects.get_current(),
            'post_detail':True})
    out['back_link'] = "/blog/posts/%s/" %author
    out['author'] = User.objects.get(username=author)
        
    from apps.ajax_replies.forms import AddReplyForm
    
    out [ 'ajax_replies_add_form' ] = AddReplyForm()
    
    out['tags'] = get_tags()
    
    return render_to_response('blog/post_detail.html', out, RequestContext(req))
コード例 #39
0
ファイル: days.py プロジェクト: gragtah/sentiment
def iso_year_start(iso_year):
    """
    The gregorian calendar date of the 
    first day of the given ISO year.
    :return: date object
    """
    fourth_jan = d(iso_year, 1, 4)
    delta = timedelta(fourth_jan.isoweekday()-1)
    return fourth_jan - delta 
コード例 #40
0
ファイル: getters.py プロジェクト: exezaid/Dpress
def post_get(year, month, day, slug, **kwargs):
    """ Returns Post object by date and slug.
    """
    from blog.models import Post
    date = d(*time.strptime(year + month + day, '%Y%m%d')[:3])
    post = Post.objects.filter(date__range=(dt.combine(date, t.min),
                                            dt.combine(date, t.max))
                               ).get(slug=slug)
    return post
コード例 #41
0
ファイル: idnum.py プロジェクト: asgeir/old-school-projects
def valid(n):
    if len(n) != 10 or (n[-1] not in '90'):
        return False

    try:
        c = 2000
        if n[-1] == '9':
            c = 1900

        d(c + int(n[4:6]), int(n[2:4]), int(n[:2]))
    except ValueError:
        return False

    s = 0
    for i in range(7, -1, -1):
        s += (2 + i % 6) * int(n[i])

    return (11 - s % 11) == int(n[-2])
コード例 #42
0
ファイル: density.py プロジェクト: gragtah/sentiment
def main():

    density = {}

    key = raw_input("Enter API key: ")

    date = d(2014,7,1)

    while (date <= d.today()):
        density = get_day(density, date, key)
        date = date + timedelta(days=1)

    pickle.dump(density, open("density.p", "wb"))
コード例 #43
0
ファイル: days.py プロジェクト: gragtah/sentiment
def get_entry(table_name, date):
    """
    Gets an entry from a specific date.
    :param date: the date of the entry to get.
    :return: the row in the table selected.
    """
    db = create_engine("sqlite:///db/app.db", echo=False)
    metadata = MetaData(db)
    days = Table(table_name, metadata, autoload=True)

    iso_date = date.isocalendar()
    if table_name == "weeks":
        date = iso_to_gregorian(iso_date[0],iso_date[1],1)
    elif table_name == "months":
        date = d(date.year, date.month, 1)
    elif table_name == "years":
        date = d(date.year, 1, 1)

    selection = days.select(days.c.date == date)
    rs = selection.execute()

    for row in rs:
        entry = row
    return entry
コード例 #44
0
ファイル: test_signal_cron.py プロジェクト: righ/bak
 def test_multiple_value(self):
     # 01-01 01:01 (*)
     d1 = self._getTarget('0,30', '0,12', '1,15', '1,6', '*')
     # 01-01-01 00:00
     self.assertTrue(d1.evalute(None, now=d(1, 1, 1, 0, 0)))
     # 01-01-01 00:30
     self.assertTrue(d1.evalute(None, now=d(1, 1, 1, 0, 30)))
     # 01-01-01 00:31
     self.assertFalse(d1.evalute(None, now=d(1, 1, 1, 0, 31)))
     # 01-01-01 12:00
     self.assertTrue(d1.evalute(None, now=d(1, 1, 1, 12, 0)))
     # 01-01-01 13:00
     self.assertFalse(d1.evalute(None, now=d(1, 1, 1, 13, 0)))
     # 01-01-15 00:00
     self.assertTrue(d1.evalute(None, now=d(1, 1, 15, 0, 0)))
     # 01-01-16 00:00
     self.assertFalse(d1.evalute(None, now=d(1, 1, 16, 0, 0)))
     # 01-06-01 00:00
     self.assertTrue(d1.evalute(None, now=d(1, 6, 1, 0, 0)))
     # 01-07-01 00:00
     self.assertFalse(d1.evalute(None, now=d(1, 7, 1, 0, 0)))
コード例 #45
0
ファイル: views.py プロジェクト: HiPiH/life
def delete_post(req, author, date, slug):
    redirect_to = reverse("blog_post_list", args=['author'])
    date = d(*time.strptime(date, '%Y-%m-%d')[:3])
    today = (dt.combine(date, t.min), dt.combine(date, t.max))
    post = get_object_or_404(Post.objects.filter(date__range=today), slug=slug, author__username=author)
    if req.user != post.author and not req.user.is_superuser:
        return HttpResponseRedirect(redirect_to)
    comments = post.get_comments()
    if req.POST and u'delete' in req.POST.keys():
        post.delete()
        last_post = Post.objects.filter(author=req.user, last_post=True).exclude(id=post.id)
        if last_post:
            last_post = last_post[0]
            last_post.last_post = False
            last_post.save()
        post_ldate = Post.objects.filter(author=req.user, published=True).exclude(id=post.id).order_by('-date')
        if post_ldate:
            post_ldate = post_ldate[0]
            post_ldate.last_post = True
            post_ldate.save()
        return HttpResponseRedirect(redirect_to)
    return render_to_response("blog/delete_confirm.html", 
                              {'post': post, 'comments': comments, 'back_link': redirect_to }, RequestContext(req))
コード例 #46
0
ファイル: jc_subscribers.py プロジェクト: DoSomething/quasar
  def runPath(self):
    """runs it all for all campaigns in cluster by opt in path"""
    for path in self.all_paths:
      tracker_date = d.utcnow()
      print (path['campaign_id'], path['opt_in_id'])
      temp_isLive = self.isLive(path['campaign_id'], path['opt_in_id'])
      live = temp_isLive[0]
      current_page = temp_isLive[1]
      active = path['campaign_status']

      if live == True or self.force == True:
        web_alpha = self.isWebAlpha(path['campaign_id'], path['opt_in_id'])
        last_page = self.binarySearch(current_page, path['campaign_id'], path['opt_in_id'])
        page_param = last_page + 1
        p_ret = 100
        last_date = self.getSubs(page_param, p_ret, path['campaign_id'], path['opt_in_id'], web_alpha)
        #double check last date by going one page down
        if last_date == d(1970, 1, 1, 0, 0):
          print ('double checking...')
          dbl_chk_page = page_param - 1
          last_date = self.getSubs(dbl_chk_page, p_ret, path['campaign_id'], path['opt_in_id'], web_alpha)
          print (last_date)

        if last_date < (d.utcnow() - t(weeks=4)) and self.force != True:
          print ('not live anymore', path['campaign_id'], path['opt_in_id'])
          q_notlive = """insert into user_processing.mobile_campaign_component (campaign_id, opt_in_id, last_date, last_page, active, live)
           VALUES ({0},{1},'{2}',{3},'{4}','False') ON DUPLICATE KEY UPDATE last_date='{2}', last_page={3}, active='{4}', live='False'""".format(path['campaign_id'], path['opt_in_id'], d.strftime(last_date, '%Y-%m-%d %H:%M:%S'), last_page, path['campaign_status'])
          self.cur.execute(q_notlive)
          self.db.commit()
        else:
          ensure_count = 2
          while tracker_date > self.stop and int(page_param) > 0:
            ensure_count -= 1
            #print path['campaign_id'], path['opt_in_id'], page_param, tracker_date
            dt = self.getSubs(page_param, p_ret, path['campaign_id'], path['opt_in_id'], web_alpha)
            tracker_date = dt
            page_param = page_param - 1
コード例 #47
0
ファイル: views.py プロジェクト: HiPiH/life
def edit_post(req, author, date, slug):
    redirect_to = reverse("blog_post_list", args=[author])
    date = d(*time.strptime(date, '%Y-%m-%d')[:3])
    today = (dt.combine(date, t.min), dt.combine(date, t.max))
    post = get_object_or_404(Post.objects.filter(date__range=today), slug=slug, author__username=author)
    if req.user != post.author and not req.user.is_superuser:
        return HttpResponseRedirect(redirect_to)
    form = PostForm(instance = post)
    if req.POST:
        form = PostForm(req.POST, instance = post)
        if form.is_valid():
            ps = form.save()
            last_post = Post.objects.filter(author=ps.author, last_post=True)
            if last_post:
                last_post = last_post[0]
                last_post.last_post = False
                last_post.save()
            post_ldate = Post.objects.filter(author=ps.author, published=True).order_by('-date')
            if post_ldate:
                post_ldate = post_ldate[0]
                post_ldate.last_post = True
                post_ldate.save()
            return HttpResponseRedirect(redirect_to)
    return render_to_response('blog/createPost.html', {'form': form, 'back_link': redirect_to, 'is_edit': 1}, RequestContext(req))
コード例 #48
0
ファイル: test_date.py プロジェクト: Alexhuszagh/XLDiscoverer
 def test_something():
     from datetime import date
     compare(date.today(), d(2001, 1, 1))
     compare(sample1.str_today_1(), '2001-01-02')
コード例 #49
0
ファイル: test_date.py プロジェクト: Alexhuszagh/XLDiscoverer
 def test_call(self, t):
     compare(t(2002, 1, 2), d(2002, 1, 2))
     from datetime import date
     dt = date(2003, 2, 1)
     self.failIf(dt.__class__ is d)
     compare(dt, d(2003, 2, 1))
コード例 #50
0
ファイル: test_date.py プロジェクト: Alexhuszagh/XLDiscoverer
 def test_add_date_supplied(self):
     from datetime import date
     date.add(d(2001, 1, 2))
     date.add(date(2001, 1, 3))
     compare(date.today(), d(2001, 1, 2))
     compare(date.today(), d(2001, 1, 3))
コード例 #51
0
ファイル: test_date.py プロジェクト: Alexhuszagh/XLDiscoverer
 def test_today_all_kw(self):
     from datetime import date
     compare(date.today(), d(2001, 2, 3))