# Correcting for Drift between Two Dates

W. eWatson notvalid2 at sbcglobal.net
Tue Sep 9 13:22:47 CEST 2008

```Steven D'Aprano wrote:
> 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.
>
>
>
Ah, ha. x.days and x.seconds.

--
W. eWatson

(121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

Web Page: <www.speckledwithstars.net/>

```