date diff calc
skip at pobox.com
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
bd = "2004-11-25"
ed = "2004-11-30"
start = datetime.date.fromtimestamp(time.strptime("%Y-%m-%d", bd))
end = datetime.date.fromtimestamp(time.strptime("%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
start = datetime.date.fromstring("%Y-%m-%d", "2004-11-25")
end = datetime.date.fromstring("%Y-%m-%d", "2004-11-30")
(Maybe it should be called "strptime", since that's the call it's saving.)
The datetime.date 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