bag.time module

Functions to make it easier to work with datetimes.

By the way, some ways of constructing a datetime instance:    -> datetime(2015, 7, 17, 2, 18, 39, 255470) -> 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:


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):
        iterable = iter(o)
    except TypeError:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)

Pyramid renderer.

Install like this:

config.add_renderer('djson', 'bag.time.djson_renderer_factory')

Like json.dumps, but using DJSONEncoder.


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

Like datetime.utcnow(), but including tzinfo.

Return type:datetime

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.