Range and datetime

Is there any particular reason that I can’t put datetime into a range?

from datetime import datetime as dt
from datetime import timedelta as delta

start = dt(1999,1,1)
stop = dt(2014,3,14)
step = delta(seconds=1800)
for timestep in range(start, stop, step):
     # sample organic simulation... 

It would also allow orbit like calculations:

start = dt(2019,1,1)
end = dt(2059,12,31)
orbit_A = delta(days=365)
orbit_B = delta(days=638)

conjunctions = set(range(start,end,orbit_A)).intersection(set(range(start,end,orbit_B)))

?

Let me add. I know that it currently doesn’t work. But is there any particular reason for this?

It’s likely because it is designed to produce integer ranges and not any other kind of range. As to why a daterange function doesn’t exist, I’m not sure, but it could be because it’s fairly simple to write an increasing generator yourself.

def daterange(start, stop, step):
     current = start
     while current < stop:
         yield current
         current += step

More suggestions can be found here.

Maybe it would be useful to add such a function? I’ve never needed it personally but I could see it being useful.

1 Like

By Bjorn Madsen via Discussions on Python.org at 28Apr2022 17:59:

Is there any particular reason that I can’t put datetime into a range?

Well the trite answer is that range() is written in C and works
directly with ints and nothing else.

However, for things which are not integers the notion of step is a
little loose. For integers this holds true:

start + n * step == start (+ step)..."n times"

For rational numbers it is well defined as well.

However for floats, addition and multiplication are
subject to rounding due to the fixed precision of floats. Datetimes
have different issues: for one thing, days are not all multiples of
24*3600 seconds in length.

It is a sane notion to work in dates and increment the day field by
1, or some whole number of days.

But incrementing a datetime by 1800 seconds will not always get the
ffect you expect. Timezones and leap seconds in particular will cause
trouble, depending on what assumptions you’re making about your desired
results.

Personally I like to work in UNIX seconds and render to datetime for
human presentation purposes. That’s not always suitable though,
particularly if you’re working in human calendar units.

Cheers,
Cameron Simpson cs@cskk.id.au

2 Likes