[Tutor] Date subtraction

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 6 Apr 2001 12:36:00 +0200


On  0, Turhan Arun <turhan@incubatr.com> wrote:
> Hi all,
> I just started learning python...
> Now, my question is:
> I want to have a user enter a date in format dd/mm/YYYY like 06/04/2001
> and another date in the same format like 22/04/2001
> depending on these two inputs. I just want to create a list of date
> strings like
> ['06/04/2001','07/04/2001','08/04/2001'....]
> It will be great if you could give some idea.

Two things: you need to parse a date, and you need to do arithmetic with it.

Parsing.

The good news is that the Python standard library has the very cool
time.strptime() function. The bad news is that it's only available on (most)
types of Unix. Luckily someone has made an implementation in Python, so if
you don't have a Unix system you can get
http://www.fukt.hk-r.se/~flognat/hacks/strptime.py and use that.

This then looks like

import time # Or import strptimeif you use that

datestr = raw_input("Give date:")
date = time.strptime(datestr, "%d/%m/%Y") # See library ref of strftime for
                                          # possible format strings
					  # use strptime.strptime in the case
					  # of the module

You know have a date in tuple format that the other time functions can use.
time.mktime(date) gives the date in seconds since 1970 (Unix time).
time.strftime("%d/%m/%Y", date) gives the same string back.

Arithmetic.

The naive way to add a day to the date is to simply add a day's worth a
seconds to the seconds since 1970, then print that date.

We get something like

import time

date1 = "06/04/2001"
date2 = "22/04/2001"

format = "%d/%m/%Y"
date1_s = time.mktime(time.strptime(date1, format)) # Get seconds
date2_s = time.mktime(time.strptime(date2, format))

if date2_s < date1_s:
   raise ValueError # Second date can't be earlier

current = date1_s
datelist = []
while 1:
    date = time.strftime(format, time.localtime(current)) # String from secs
    datelist.append(date)
    if (date == date2) or (current > date2_s):
        break
    current += 24*60*60 # Add one day

print datelist

(this is untested)

This is naive because there may be things like leap seconds and whatnot,
breaking this code.
mxDateTime is a package that's intended for handling date arithmetic, so if
you want a great program you should look at that. I never used it myself,
but it has a great reputation:
http://www.lemburg.com/files/python/mxDateTime.html

-- 
Remco Gerlich