示例#1
0
def test_common_strings():
    c1 = Chronyk("today").relativestring()
    c2 = Chronyk("now").relativestring()
    c3 = Chronyk("this week").relativestring()
    c4 = Chronyk("this month").relativestring()
    c5 = Chronyk("this day").relativestring()
    assert c1 == c2 and c2 == c3 and c3 == c4 and c4 == c5
示例#2
0
def build_item_filter(args):
    """ Parse arguments for playlist item filter criteria. """
    item_filter = PlaylistItemFilter()
    if args.added_since is not None:
        item_filter.added_since = datetime.datetime.fromtimestamp(
            Chronyk(args.added_since).timestamp(), pytz.utc)
    if args.published_since is not None:
        item_filter.published_since = datetime.datetime.fromtimestamp(
            Chronyk(args.published_since).timestamp(), pytz.utc)
    if args.name is not None:
        item_filter.name = args.name

    return item_filter
示例#3
0
def main():
    # main block, processing received arguments and general flow
    args = sys.argv[1:]
    if len(args) == 0:
        last_url = _main_url + 'last/'
        last_xml = get_xml(last_url)
        last_record = parse_xml(last_xml)
        format_output_value(last_record)
    elif len(args) == 1:
        if not args[0] == "--help":
            print(_wrong_parameters_message)
            print(_help_message)
            sys.exit(2)
        print(_help_message)
        sys.exit(0)
    elif len(args) == 4:
        options = {}
        if not args[0] == "--from":
            print(_wrong_parameters_message)
            print(_help_message)
            sys.exit(2)
        options[args[0]] = args[1]
        if not args[2] == "--to":
            print(_wrong_parameters_message)
            print(_help_message)
            sys.exit(2)
        options[args[2]] = args[3]
        from_value = options['--from']
        to_value = options['--to']
        from_timestamp = convert_to_timestamp(from_value)
        to_timestamp = convert_to_timestamp(to_value)
        validate_timestamps(from_timestamp, to_timestamp)
        print("Requested records:\nFrom  {0}\nTo    {1}".format(
            Chronyk(from_value).ctime(),
            Chronyk(to_value).ctime()))
        try:
            summary_record = get_summary_record(from_timestamp, to_timestamp)
        except KeyboardInterrupt:
            print("\nProgram interrupted by user, exiting.")
            sys.exit(1)
        try:
            format_output_value(summary_record)
        except MemoryError:
            print(_out_of_memory)
            sys.exit(1)
    else:
        print(_wrong_parameters_message)
        print(_help_message)
        sys.exit(2)
    return True
示例#4
0
    def do(self, event):
        record = dict(event.record)
        time = Chronyk(record[self._key])
        if self._format is None:
            record[self._key] = time.timestamp()
        else:
            record[self._key] = time.timestring(self._format)

        return Event(event.tag, event.timestamp, record)
示例#5
0
def test_relative_months_2():
    dati = datetime.datetime.utcnow()
    newmonth = (((dati.month - 1) + 4) % 12) + 1
    newyear = dati.year + int(((dati.month - 1) + 4) / 12)
    newday = dati.day
    while newday > calendar.monthrange(newyear, newmonth)[1]:
        newday -= 1
    dati = dati.replace(year=newyear, month=newmonth, day=newday)
    timestr = time.strftime("%Y-%m-%d", dati.timetuple())
    assert Chronyk("in 4 months", timezone=0).relativestring() == timestr
示例#6
0
    def do(self, event):
        record = event.record
        time = Chronyk(record[self._time_key])
        path = time.timestring(self._path_template)
        path = path.format(**record)
        if path not in self._buffer:
            self._buffer[path] = list()

        self._buffer[path].append(record)

        if len(self._buffer[path]) > self._buffer_size:
            self.flush_one(path)

        return event
示例#7
0
    def do(self, event):
        record = event.record
        timestamp = Chronyk(record[self._time_key])
        tablename = timestamp.timestring(self._table_template)
        tablename = tablename.format(**record)
        if tablename not in self._buffer:
            self._buffer[tablename] = list()

        self._buffer[tablename].append(record)

        if len(self._buffer[tablename]) > self._buffer_size:
            self.flush_one(tablename)

        return event
示例#8
0
def convert_to_timestamp(relative_time):
    # converting received relative time to timestamp
    try:
        timestamp = int(Chronyk(relative_time).timestamp())
    except TypeError:
        print(_bad_time_received)
        print(_help_message)
        sys.exit(1)
    except ValueError:
        print(_bad_time_received)
        print(_help_message)
        sys.exit(1)
    else:
        timestamp -= timestamp % 60
        return timestamp
示例#9
0
def timeslate():
    input_time = request.args.get('input')
    output_format = request.args.get('format')
    tz = int(request.args.get('tz', '0'))
    if not input_time:
        return error("input parameter is required"), 500
    try:
        input_time = int(input_time)
    except ValueError:
        pass
    try:
        sanitized = Chronyk(input_time, timezone=tz)
    except:
        return error("Timeslate does not accept this input format."), 500
    output = {
        'ctime': sanitized.ctime(),
        'timestring': sanitized.timestring(),
        'timestamp': sanitized.timestamp(),
        'input': input_time
    }
    if output_format:
        output['formatted'] = sanitized.timestring(output_format)
    return json.dumps(output)
示例#10
0
def test_relative_seconds_2():
    assert Chronyk("in 5 seconds").relativestring() == "just now"
示例#11
0
def test_relative_seconds_1():
    assert Chronyk("2 seconds ago").relativestring() == "just now"
示例#12
0
def test_relative_now():
    assert Chronyk().relativestring() == "just now"
示例#13
0
def test_absolute_value():
    with pytest.raises(ValueError):
        Chronyk("warglblargl")
示例#14
0
def test_absolute_24hr_seconds():
    t = Chronyk("17:14:32")
    assert t.ctime()[11:-5] == "17:14:32"
示例#15
0
def test_none_con():
    assert isEqual(Chronyk(None).timestamp(), Chronyk(time.time()).timestamp())
示例#16
0
def test(input_string):
    output = Chronyk(input_string)
    print(output)
示例#17
0
def test_empty_con():
    assert isEqual(Chronyk().timestamp(), time.time())
示例#18
0
def test_absolute_iso_date():
    t = Chronyk("2014-09-18")
    assert t.ctime() == "Thu Sep 18 00:00:00 2014"
示例#19
0
def test_absolute_written_1():
    t = Chronyk("May 2nd, 2015")
    assert t.ctime() == "Sat May  2 00:00:00 2015"
示例#20
0
def test_absolute_iso():
    t = Chronyk("2014-09-18 11:24:47")
    assert t.ctime() == "Thu Sep 18 11:24:47 2014"
示例#21
0
def test_pre_epoch_2():
    assert Chronyk(time.strptime("1950 01 01", "%Y %m %d")).timestring("%Y %m %d") == "1950 01 01"
示例#22
0
def test_pre_epoch_1():
    assert Chronyk(datetime.datetime(1950, 1, 1)).datetime() == datetime.datetime(1950, 1, 1)
示例#23
0
def test_yesteryear():
    assert Chronyk("yesteryear").relativestring() == Chronyk("1 year ago").relativestring()
示例#24
0
def test_yesterday():
    assert Chronyk("yesterday").relativestring() == "yesterday"
示例#25
0
文件: test.py 项目: hayd/Chronyk
def main():
    currentutc()

    # Constructor - None / Timestamp
    assert isEqual(Chronyk().timestamp(), time.time())
    assert isEqual(Chronyk(None).timestamp(), Chronyk(time.time()).timestamp())

    # Constructor - Common Strings
    c1 = Chronyk("today").relativestring()
    c2 = Chronyk("now").relativestring()
    c3 = Chronyk("this week").relativestring()
    c4 = Chronyk("this month").relativestring()
    c5 = Chronyk("this day").relativestring()
    assert c1 == c2 and c2 == c3 and c3 == c4 and c4 == c5
    assert Chronyk("yesterday").relativestring() == "yesterday"
    assert Chronyk("yesteryear").relativestring() == Chronyk(
        "1 year ago").relativestring()

    # Constructor - Absolute Strings
    t = Chronyk("2014-09-18 11:24:47")
    assert t.ctime() == "Thu Sep 18 11:24:47 2014"
    t = Chronyk("2014-09-18")
    assert t.ctime() == "Thu Sep 18 00:00:00 2014"
    t = Chronyk("May 2nd, 2015")
    assert t.ctime() == "Sat May  2 00:00:00 2015"
    t = Chronyk("2. August 2010")
    assert t.ctime() == "Mon Aug  2 00:00:00 2010"
    t = Chronyk("11:14 am")
    assert t.ctime()[11:-5] == "11:14:00"
    t = Chronyk("11:14:32 am")
    assert t.ctime()[11:-5] == "11:14:32"
    t = Chronyk("17:14")
    assert t.ctime()[11:-5] == "17:14:00"
    t = Chronyk("17:14:32")
    assert t.ctime()[11:-5] == "17:14:32"

    # Constructor - Relative Strings
    # seconds
    assert Chronyk().relativestring() == "just now"
    assert Chronyk("2 seconds ago").relativestring() == "just now"
    assert Chronyk("in 5 seconds").relativestring() == "just now"
    timest = time.time()
    assert Chronyk(timest - 5).relativestring(now=timest,
                                              minimum=0) == "5 seconds ago"
    # minutes
    assert Chronyk("1 minute ago").relativestring() == "1 minute ago"
    assert Chronyk("in 2 minutes").relativestring() == "in 2 minutes"
    # hours
    assert Chronyk("1 hour ago").relativestring() == "1 hour ago"
    assert Chronyk("in 2 hours").relativestring() == "in 2 hours"
    # days
    assert Chronyk("10 days ago").relativestring() == "10 days ago"
    assert Chronyk("in 20 days").relativestring() == "in 20 days"
    # weeks
    assert Chronyk("1 week ago").relativestring() == "7 days ago"
    assert Chronyk("in 2 weeks").relativestring() == "in 14 days"
    assert Chronyk(
        "in blurgh weeks and 2 days").relativestring() == "in 2 days"
    # months
    assert Chronyk("overninethousand months and 2 days ago").relativestring(
    ) == "2 days ago"
    dati = datetime.datetime.utcnow()
    newmonth = (((dati.month - 1) + 4) % 12) + 1
    newyear = dati.year + (((dati.month - 1) + 4) / 12)
    dati = dati.replace(year=int(newyear), month=int(newmonth))
    while dati.day > calendar.monthrange(dati.year, dati.month)[1]:
        dati = dati.replace(day=dati.day - 1)
    timestr = time.strftime("%Y-%m-%d", dati.timetuple())
    assert Chronyk("in 4 months").relativestring() == timestr
    # years
    assert Chronyk(
        "something years and 2 days ago").relativestring() == "2 days ago"
    dati = datetime.datetime.utcnow()
    dati = dati.replace(year=dati.year - 2)
    timestr = time.strftime("%Y-%m-%d", dati.timetuple())
    assert Chronyk("2 years ago").relativestring() == timestr

    # Constructor - Struct time
    timestr = time.localtime()
    assert Chronyk(timestr).timestamp() == time.mktime(timestr)

    # Constructor - date range validation
    Chronyk("2 hours ago", allowfuture=False, allowpast=True)
    Chronyk("in 2 hours", allowfuture=True, allowpast=False)
    try:
        Chronyk("2 hours ago", allowpast=False)
    except DateRangeError:
        pass
    else:
        raise DateRangeError
    try:
        Chronyk("in 2 hours", allowfuture=False)
    except DateRangeError:
        pass
    else:
        raise DateRangeError

    try:
        Chronyk(["this", "should", "throw", "TypeError"])
    except TypeError:
        pass
    else:
        raise TypeError

    # Datetime
    timest = currentutc()
    assert Chronyk(
        timest,
        timezone=0).datetime() == datetime.datetime.fromtimestamp(timest)

    # Timestamp
    timest = time.time()
    assert Chronyk(timest).timestamp() == timest
    assert Chronyk(timest,
                   timezone=0).timestamp(timezone=-7200) == timest + 7200
    assert Chronyk(timest,
                   timezone=-7200).timestamp(timezone=0) == timest - 7200

    # Timestring
    timest = time.time()
    assert Chronyk(timest).timestring() == time.strftime(
        "%Y-%m-%d %H:%M:%S", time.gmtime(timest))
    assert Chronyk(timest).timestring("%Y-%m-%d") == time.strftime(
        "%Y-%m-%d", time.gmtime(timest))

    print("All tests successfull.")
示例#26
0
def test_absolute_12hr():
    t = Chronyk("11:14 am")
    assert t.ctime()[11:-5] == "11:14:00"
示例#27
0
def test_absolute_12hr_seconds():
    t = Chronyk("11:14:32 am")
    assert t.ctime()[11:-5] == "11:14:32"
示例#28
0
def test_absolute_24hr():
    t = Chronyk("17:14")
    assert t.ctime()[11:-5] == "17:14:00"
示例#29
0
def test_absolute_written_2():
    t = Chronyk("2. August 2010")
    assert t.ctime() == "Mon Aug  2 00:00:00 2010"
示例#30
0
def test_delta_operators_add():
    timest = time.time()
    assert ChronykDelta(5) + ChronykDelta(-5) == 0
    assert ChronykDelta(5) + Chronyk(timest) == Chronyk(timest + 5)
    assert ChronykDelta(5) + 10 == 15