sqlalchemy timedelta property

datetime, sqlalchemy, timedelta

Solution

So from what I get in the question, you want to just store an interval and take it out of the database to use it again? But you want to understand how it is stored?

Concerning the storage: This is probably easier with Unix timestamps than with DateTimes. Suppose you want to store `timedelta(1)`, i.e. a delta of one day. What is stored in the database is the time since the "epoch", i.e. second "0" in Unix timestamps and as a date: `1970-01-01 00:00:00` (this is where Unix timestamps start counting the seconds). If you don't know about epoch or timestamp, then read Wikipedia on Unix time.

So we want to store one day of difference? The documentation claims it stored "time since epoch". We just learned "epoch" is "second 0", so a day later would be 60 seconds per minute, 60 minutes per hour, 24 hours per day: `60 * 60 * 24 = 86400`. So stored as an integer this is easy to understand: If you find the value `86400` in your database, then it means `1 day, 0 hours, 0 minutes, 0 seconds`.

Reality is a bit different: It does not store an integer but a `DateTime` object. Speaking from this perspective, the epoch is `1970-01-01 00:00:00`. So what is a delta of one day since the epoch? That is easy: it's `1970-01-02 00:00:00`. You can see, it is a day later.

An hour later? `1970-01-01 01:00:00`.

Two days, four hours, 30 seconds?: `1970-01-03 04:00:30`.

And you could even do it yourself:

epoch = datetime.utcfromtimestamp(0)
delta = timedelta(1)
one_day = datetime.utcfromtimestamp(86400)
print "Date to be stored in database:", epoch + delta
print "Timedelta from date:", one_day - epoch

As you can see, the calculation is easy and this is all that is done behind the scenes. Take a look at this full example:

interval = IntervalItem(interval=delta)
session.add(interval)
i = session.query(IntervalItem).first()
print "Timedelta from database:", i.interval

You can see it is no different from the above example except it goes through the database. The only thing to keep in mind with this, is this note:

Note that the Interval type does not currently provide date arithmetic operations 
on platforms which do not support interval types natively.

That means you should be careful how you use it, for example addition in the query might not be a good idea, but you should just play around with it.

Problem

I need to save a time interval in a column in a table. based on: http://docs.sqlalchemy.org/en/rel_0_8/core/types.html I can use Interval type for that. My database is SQLite, and I don't quite understand this description in the document: ``` "The Interval type deals with datetime.timedelta objects. In PostgreSQL, the native INTERVAL type is used; for others, the value is stored as a date which is relative to the “epoch” (Jan. 1, 1970)." ``` Can anybody tell me how should I do that?

Original source