Correcting for Drift between Two Dates

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Sep 9 03:41:41 EDT 2008


On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote:

> I have two dates, ts1, ts2 as below in the sample program. I know the
> clock drift in seconds per day. I would like to calculate the actual
> date of ts2. See my question at the end of the program.


When faced with a complicated task, break it down into simpler subtasks. 
Functions are your friends. Here you go:



from __future__ import division

from datetime import datetime as DT
from datetime import timedelta

SITE_DRIFT = 4.23  # drift in seconds per day
# negative drift means the clock falls slow
SEC_PER_DAY = 60*60*24  # number of seconds per day


def calc_drift(when, base, drift=SITE_DRIFT):
    """Return the amount of drift at date when since date base."""
    x = when - base
    days = x.days + x.seconds/SEC_PER_DAY
    return drift*days

def fix_date(when, base, drift=SITE_DRIFT):
    """Return date when adjusted to the correct time."""
    d = calc_drift(when, base, drift)
    delta = timedelta(seconds=-d)
    return when + delta


And here it is in action:

>>> fix_date(DT(2008,9,9), DT(2008,9,8))
datetime.datetime(2008, 9, 8, 23, 59, 55, 770000)



I leave it to you to convert date/time strings into datetime objects.



-- 
Steven



More information about the Python-list mailing list