Welcome to tempora documentation!

Objects and routines pertaining to date and time (tempora)

class tempora.DatetimeConstructor

Bases: object

>>> cd = DatetimeConstructor.construct_datetime
>>> cd(datetime.datetime(2011,1,1))
datetime.datetime(2011, 1, 1, 0, 0)
classmethod construct_datetime(*args, **kwargs)

Construct a datetime.datetime from a number of different time types found in python and pythonwin

class tempora.Parser(formats=None)

Bases: object

Datetime parser: parses a date-time string using multiple possible formats.

>>> p = Parser(('%H%M', '%H:%M'))
>>> tuple(p.parse('1319'))
(1900, 1, 1, 13, 19, 0, 0, 1, -1)
>>> dateParser = Parser(('%m/%d/%Y', '%Y-%m-%d', '%d-%b-%Y'))
>>> tuple(dateParser.parse('2003-12-20'))
(2003, 12, 20, 0, 0, 0, 5, 354, -1)
>>> tuple(dateParser.parse('16-Dec-1994'))
(1994, 12, 16, 0, 0, 0, 4, 350, -1)
>>> tuple(dateParser.parse('5/19/2003'))
(2003, 5, 19, 0, 0, 0, 0, 139, -1)
>>> dtParser = Parser(('%Y-%m-%d %H:%M:%S', '%a %b %d %H:%M:%S %Y'))
>>> tuple(dtParser.parse('2003-12-20 19:13:26'))
(2003, 12, 20, 19, 13, 26, 5, 354, -1)
>>> tuple(dtParser.parse('Tue Jan 20 16:19:33 2004'))
(2004, 1, 20, 16, 19, 33, 1, 20, -1)

Be forewarned, a ValueError will be raised if more than one format matches:

>>> Parser(('%H%M', '%H%M%S')).parse('732')
Traceback (most recent call last):
        ...
ValueError: More than one format string matched target 732.
formats = ('%m/%d/%Y', '%m/%d/%y', '%Y-%m-%d', '%d-%b-%Y', '%d-%b-%y')

some common default formats

parse(target)
tempora.calculate_prorated_values()

A utility function to prompt for a rate (a string in units per unit time), and return that same rate for various time periods.

tempora.date_range(start=None, stop=None, step=None)

Much like the built-in function range, but works with dates

>>> range_items = date_range(
...     datetime.datetime(2005,12,21),
...     datetime.datetime(2005,12,25),
... )
>>> my_range = tuple(range_items)
>>> datetime.datetime(2005,12,21) in my_range
True
>>> datetime.datetime(2005,12,22) in my_range
True
>>> datetime.datetime(2005,12,25) in my_range
False
tempora.datetime_mod(dt, period, start=None)

Find the time which is the specified date/time truncated to the time delta relative to the start date/time. By default, the start time is midnight of the same day as the specified date/time.

>>> datetime_mod(datetime.datetime(2004, 1, 2, 3),
...     datetime.timedelta(days = 1.5),
...     start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
...     datetime.timedelta(days = 1.5),
...     start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 2, 12, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
...     datetime.timedelta(days = 7),
...     start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 10, 13),
...     datetime.timedelta(days = 7),
...     start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 8, 0, 0)
tempora.datetime_round(dt, period, start=None)

Find the nearest even period for the specified date/time.

>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 11, 13),
...     datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 8, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 31, 13),
...     datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 30),
...     datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
tempora.divide_timedelta(td1, td2)

Get the ratio of two timedeltas

>>> one_day = datetime.timedelta(days=1)
>>> one_hour = datetime.timedelta(hours=1)
>>> divide_timedelta(one_hour, one_day) == 1 / 24
True
tempora.divide_timedelta_float(td, divisor)

Divide a timedelta by a float value

>>> one_day = datetime.timedelta(days=1)
>>> half_day = datetime.timedelta(days=.5)
>>> divide_timedelta_float(one_day, 2.0) == half_day
True
>>> divide_timedelta_float(one_day, 2) == half_day
True
tempora.get_date_format_string(period)

For a given period (e.g. ‘month’, ‘day’, or some numeric interval such as 3600 (in secs)), return the format string that can be used with strftime to format that time to specify the times across that interval, but no more detailed. For example,

>>> get_date_format_string('month')
'%Y-%m'
>>> get_date_format_string(3600)
'%Y-%m-%d %H'
>>> get_date_format_string('hour')
'%Y-%m-%d %H'
>>> get_date_format_string(None)
Traceback (most recent call last):
        ...
TypeError: period must be a string or integer
>>> get_date_format_string('garbage')
Traceback (most recent call last):
        ...
ValueError: period not in (second, minute, hour, day, month, year)
tempora.get_nearest_year_for_day(day)

Returns the nearest year to now inferred from a Julian date.

tempora.get_period_seconds(period)

return the number of seconds in the specified period

>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
tempora.gregorian_date(year, julian_day)

Gregorian Date is defined as a year and a julian day (1-based index into the days of the year).

>>> gregorian_date(2007, 15)
datetime.date(2007, 1, 15)
tempora.osc_per_year = 290091329207984000

mean vernal equinox year expressed in oscillations of atomic cesium at the year 2000 (see http://webexhibits.org/calendars/timeline.html for more info).

tempora.parse_timedelta(str)

Take a string representing a span of time and parse it to a time delta. Accepts any string of comma-separated numbers each with a unit indicator.

>>> parse_timedelta('1 day')
datetime.timedelta(days=1)
>>> parse_timedelta('1 day, 30 seconds')
datetime.timedelta(days=1, seconds=30)
>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')
datetime.timedelta(days=47, seconds=28848, microseconds=15400)

Supports weeks, months, years

>>> parse_timedelta('1 week')
datetime.timedelta(days=7)
>>> parse_timedelta('1 year, 1 month')
datetime.timedelta(days=395, seconds=58685)

Note that months and years strict intervals, not aligned to a calendar:

>>> now = datetime.datetime.now()
>>> later = now + parse_timedelta('1 year')
>>> diff = later.replace(year=now.year) - now
>>> diff.seconds
20940
tempora.strftime(fmt, t)

A class to replace the strftime in datetime package or time module. Identical to strftime behavior in those modules except supports any year. Also supports datetime.datetime times. Also supports milliseconds using %s Also supports microseconds using %u

tempora.strptime(s, fmt, tzinfo=None)

A function to replace strptime in the time module. Should behave identically to the strptime function except it returns a datetime.datetime object instead of a time.struct_time object. Also takes an optional tzinfo parameter which is a time zone info object.

class tempora.timing.BackoffDelay(*args, **kwargs)

Bases: object

Exponential backoff delay.

Useful for defining delays between retries. Consider for use with jaraco.functools.retry_call as the cleanup.

Default behavior has no effect; a delay or jitter must be supplied for the call to be non-degenerate.

>>> bd = BackoffDelay()
>>> bd()
>>> bd()

The following instance will delay 10ms for the first call, 20ms for the second, etc.

>>> bd = BackoffDelay(delay=0.01, factor=2)
>>> bd()
>>> bd()

Inspect and adjust the state of the delay anytime.

>>> bd.delay
0.04
>>> bd.delay = 0.01

Set limit to prevent the delay from exceeding bounds.

>>> bd = BackoffDelay(delay=0.01, factor=2, limit=0.015)
>>> bd()
>>> bd.delay
0.015

To reset the backoff, simply call .reset():

>>> bd.reset()
>>> bd.delay
0.01

Iterate on the object to retrieve/advance the delay values.

>>> next(bd)
0.01
>>> next(bd)
0.015
>>> import itertools
>>> tuple(itertools.islice(bd, 3))
(0.015, 0.015, 0.015)

Limit may be a callable taking a number and returning the limited number.

>>> at_least_one = lambda n: max(n, 1)
>>> bd = BackoffDelay(delay=0.01, factor=2, limit=at_least_one)
>>> next(bd)
0.01
>>> next(bd)
1

Pass a jitter to add or subtract seconds to the delay.

>>> bd = BackoffDelay(jitter=0.01)
>>> next(bd)
0
>>> next(bd)
0.01

Jitter may be a callable. To supply a non-deterministic jitter between -0.5 and 0.5, consider:

>>> import random
>>> jitter=functools.partial(random.uniform, -0.5, 0.5)
>>> bd = BackoffDelay(jitter=jitter)
>>> next(bd)
0
>>> 0 <= next(bd) <= 0.5
True
bump()
delay = 0
factor = 1

Multiplier applied to delay

jitter = 0

Number or callable returning extra seconds to add to delay

reset()
class tempora.timing.IntervalGovernor(min_interval)

Bases: object

Decorate a function to only allow it to be called once per min_interval. Otherwise, it returns None.

decorate(func)
class tempora.timing.Stopwatch

Bases: object

A simple stopwatch which starts automatically.

>>> w = Stopwatch()
>>> _1_sec = datetime.timedelta(seconds=1)
>>> w.split() < _1_sec
True
>>> import time
>>> time.sleep(1.0)
>>> w.split() >= _1_sec
True
>>> w.stop() >= _1_sec
True
>>> w.reset()
>>> w.start()
>>> w.split() < _1_sec
True

It should be possible to launch the Stopwatch in a context:

>>> with Stopwatch() as watch:
...     assert isinstance(watch.split(), datetime.timedelta)

In that case, the watch is stopped when the context is exited, so to read the elapsed time:

>>> watch.elapsed

datetime.timedelta(…) >>> watch.elapsed.seconds 0

reset()
split()
start()
stop()
class tempora.timing.Timer(target=inf)

Bases: tempora.timing.Stopwatch

Watch for a target elapsed time.

>>> t = Timer(0.1)
>>> t.expired()
False
>>> __import__('time').sleep(0.15)
>>> t.expired()
True
expired()

Classes for calling functions a schedule.

class tempora.schedule.CallbackScheduler(dispatch)

Bases: tempora.schedule.Scheduler

Command targets are passed to a dispatch callable on schedule.

run(command)

Run the command

class tempora.schedule.DelayedCommand

Bases: datetime.datetime

A command to be executed after some delay (seconds or timedelta).

classmethod after(delay, target)
classmethod at_time(at, target)

Construct a DelayedCommand to come due at at, where at may be a datetime or timestamp.

due()
classmethod from_datetime(other)
class tempora.schedule.InvokeScheduler

Bases: tempora.schedule.Scheduler

Command targets are functions to be invoked on schedule.

run(command)

Run the command

class tempora.schedule.PeriodicCommand

Bases: tempora.schedule.DelayedCommand

Like a delayed command, but expect this command to run every delay seconds.

next()
class tempora.schedule.PeriodicCommandFixedDelay

Bases: tempora.schedule.PeriodicCommand

Like a periodic command, but don’t calculate the delay based on the current time. Instead use a fixed delay following the initial run.

classmethod at_time(at, delay, target)

Construct a DelayedCommand to come due at at, where at may be a datetime or timestamp.

classmethod daily_at(at, target)

Schedule a command to run at a specific time each day.

class tempora.schedule.Scheduler

Bases: object

A rudimentary abstract scheduler accepting DelayedCommands and dispatching them on schedule.

add(command)
abstract run(command)

Run the command

run_pending()
tempora.schedule.from_timestamp(ts)

Convert a numeric timestamp to a timezone-aware datetime.

A client may override this function to change the default behavior, such as to use local time or timezone-naïve times.

tempora.schedule.now()

Provide the current timezone-aware datetime.

A client may override this function to change the default behavior, such as to use local time or timezone-naïve times.

Facilities for common time operations in UTC.

Inspired by the utc project.

>>> dt = now()
>>> dt == fromtimestamp(dt.timestamp())
True
>>> dt.tzinfo
datetime.timezone.utc
>>> from time import time as timestamp
>>> now().timestamp() - timestamp() < 0.1
True
>>> (now() - fromtimestamp(timestamp())).total_seconds() < 0.1
True
>>> datetime(2018, 6, 26, 0).tzinfo
datetime.timezone.utc
>>> time(0, 0).tzinfo
datetime.timezone.utc
tempora.utc.fromtimestamp()

timestamp[, tz] -> tz’s local time from POSIX timestamp.

tempora.utc.now()

Returns new datetime object representing current time local to tz.

tz

Timezone object.

If no tz is specified, uses local timezone.

Indices and tables