bag.time module

Functions to make it easier to work with datetimes.

By the way, some ways of constructing a datetime instance:

datetime.now()    -> datetime(2015, 7, 17, 2, 18, 39, 255470)
datetime.now(utc) -> datetime(2015, 7, 17, 5, 18, 39, 255497, tzinfo=<UTC>)
datetime.utcnow() -> datetime(2015, 7, 17, 5, 18, 39, 255543)
class bag.time.DJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: json.encoder.JSONEncoder

JSON encoder that outputs dates and decimals.

Example usage:

DJSONEncoder().encode([datetime.datetime.now()])
'["2015-01-21T14:42:28"]'
default(obj)[source]

Implement this method in a subclass such that it returns a serializable object for o, or calls the base implementation (to raise a TypeError).

For example, to support arbitrary iterators, you could implement default like this:

def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
bag.time.djson_renderer_factory(info)[source]

Pyramid renderer.

Install like this:

config.add_renderer('djson', 'bag.time.djson_renderer_factory')
bag.time.dumps(value)[source]

Like json.dumps, but using DJSONEncoder.

bag.time.naive(dt)[source]

Remove the timezone from a datetime instance.

Return type

datetime

bag.time.now_or_future(dt, timezone=<UTC>, now=None)[source]

If given datetime is in the past, default to now.

Given a datetime, returns it as long as it is not in the past; otherwise, returns now. You may pass the timezone instance for the comparison (defaults to UTC); this is useful if your datetime is naive.

The argument now should be ignored; it is used only in the unit tests.

Return type

datetime

bag.time.now_with_tz()[source]

Like datetime.utcnow(), but including tzinfo.

Return type

datetime

bag.time.parse_iso_datetime(text)[source]

Convert the given string to a naive (no tzinfo) datetime.

Return type

datetime

bag.time.simplify_datetime(val, granularity='minute')[source]

Notice this throws away any tzinfo.

Return type

datetime

bag.time.timed_call(seconds, function, repetitions=- 1, *a, **kw)[source]

Perform some task every x seconds. Sleep if necessary.

Do not sleep after the last turn.

By default, runs forever. To control the number of times that function should run, pass in a number of repetitions. Returns immediately if repetitions is zero.