date diff calc

Skip Montanaro skip at
Mon Nov 29 20:02:40 CET 2004

    tertius> Is there a more pythonic way to write or do a date difference
    tertius> calculation? I have as input two date fields in the form
    tertius> 'YYYY-MM-DD'

How about:

    import datetime
    import time

    bd = "2004-11-25"
    ed = "2004-11-30"

    start ="%Y-%m-%d", bd))
    end ="%Y-%m-%d", ed))

    print ed , '-', bd , '=', (end-start).days

I think that for completeness' sake it would be nice if datetime exposed a
fromstring method which accepted a string representing a date and a format
specifier, e.g.:

    start ="%Y-%m-%d", "2004-11-25")
    end ="%Y-%m-%d", "2004-11-30")

(Maybe it should be called "strptime", since that's the call it's saving.)

The object already exposes a strftime method for generating a
formatted string output and will create date objects from both time.time()
output (fromtimestamp) and "proleptic Gregorian ordinal"s (fromordinal).
Looking at the datetime module docs, it's not at all obvious to me that the
latter would be used all that often.  I think inputs from strings would be
much more common.


More information about the Python-list mailing list