Introduction

For a recent project of mine I started using PostgreSQL’s tsrange type and needed an equivalent in Python. These range types attempt to mimick PostgreSQL’s behavior in every way. To make ranges more useful some extra methods have been added that are not available in PostgreSQL.

Requirements

Spans have no requirements but the standard library. It is known to work on the following Python versions

  • Python 2.7

  • Python 3.3

  • Python 3.4

  • Python 3.5

  • Python 3.6

  • PyPy

  • PyPy3

It may work on other version as well.

Installation

Spans is available from PyPI.

$ pip install spans

Example

If you are making a booking application for a bed and breakfast hotel and want to ensure no room gets double booked:

 1 from collections import defaultdict
 2 from datetime import date
 3 from spans import daterange
 4
 5 # Add a booking from 2013-01-14 through 2013-01-15
 6 bookings = defaultdict(list, {
 7     1 : [daterange(date(2013, 1, 14), date(2013, 1, 16))]
 8 }
 9
10 def is_valid_booking(bookings, room, new_booking):
11     return not any(booking.overlap(new_booking for booking in bookings[room])
12
13 print is_valid_booking(
14     bookings, 1, daterange(date(2013, 1, 14), date(2013, 1, 18))) # False
15 print is_valid_booking(
16     bookings, 1, daterange(date(2013, 1, 16), date(2013, 1, 18))) # True

Using with Psycopg

To use Spans with Psycopg the Psycospans project exists.