473,373 Members | 1,611 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,373 software developers and data experts.

date diff calc

Hi,

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

TIA
Terius

from datetime import date

bdl = '2004-11-25'.split('-')
edl = '2004-11-30'.split('-')
bd = date(int(bdl[0]), int(bdl[1]), int(bdl[2]))
ed = date(int(edl[0]), int(edl[1]), int(edl[2]))

print ed , '-', bd , '=', (ed-bd).days
Jul 18 '05 #1
9 4374
> bdl = '2004-11-25'.split('-')
edl = '2004-11-30'.split('-')
bd = date(int(bdl[0]), int(bdl[1]), int(bdl[2]))
ed = date(int(edl[0]), int(edl[1]), int(edl[2]))
using time.strptime and datetime.date.fromtimestamp is surely the better
alternative, as it lets specify you the format by a string.
print ed , '-', bd , '=', (ed-bd).days


I can't imagine what could possibly be easier than subtracting two dates -
in fact, most times one has to jump through much more hoops to achieve
these results, e.g. in java.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #2
Diez B. Roggisch wrote:

I can't imagine what could possibly be easier than subtracting two dates -
in fact, most times one has to jump through much more hoops to achieve
these results, e.g. in java.

I'll try that.

Thanks,
T
Jul 18 '05 #3

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 = 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
specifier, e.g.:

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.

Skip
Jul 18 '05 #4
Here's how to do it as a one-liner:

python -c "import datetime; import time; print 'Only %d days until
Christmas' % (datetime.date(2004, 12, 25) -
datetime.date.fromtimestamp(time.time())).days"

Here's a slightly shorter way of doing it:

python -c "import time; print 'Only %f more days until Christmas' %
(float(time.mktime(time.strptime('2004-12-25', '%Y-%m-%d')) -
time.time()) / 86400)"
Jul 18 '05 #5
[Skip Montanaro]
...
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.
Then the part of the docs you're overlooking is the part explaining
that "Calendrical Calculations" bases all its calendar conversions on
proleptic Gregorian ordinals. They're for people who want something
other than the Gregorian calendar, and want it enough to write some
code.
I think inputs from strings would be much more common.


Me too, although it's a bottomless pit.

guess-6-intended-meanings-for-1/2/3-before-breakfast-ly y'rs
Jul 18 '05 #6
Tim Peters wrote:
[Skip Montanaro]
I think inputs from strings would be much more common.


Me too, although it's a bottomless pit.

guess-6-intended-meanings-for-1/2/3-before-breakfast-ly y'rs


I think Skip was intending that the format string be mandatory,
to avoid such ambiguity. At least, that's what I inferred from
his example, where the format string came before the date string:

start = datetime.date.fromstring("%Y-%m-%d", "2004-11-25")

-Peter
Jul 18 '05 #7
[Skip Montanaro]
I think inputs from strings would be much more common.

[Tim Peters] Me too, although it's a bottomless pit.

guess-6-intended-meanings-for-1/2/3-before-breakfast-ly y'rs

[Peter Hansen] I think Skip was intending that the format string be mandatory,
to avoid such ambiguity. At least, that's what I inferred from
his example, where the format string came before the date string:

start = datetime.date.fromstring("%Y-%m-%d", "2004-11-25")


It's still a bottomless pit -- ask Brett, who implemented the Python
strptime <wink>. But now that we *have* a portable strptime
implementation, perhaps it would be OK to teach datetime about it.

OTOH, is that what people really want? For all I know,
rfc822.getdate() or rfc822.getdate_tz() are what's really wanted, or
maybe some DWIM thing like Zope's date guessers.

Does anyone want any of those enough to write the code, tests, and
docs? If so, the first person to do so will probably win the debate
....
Jul 18 '05 #8
Tim Peters wrote:
[Peter Hansen]
I think Skip was intending that the format string be mandatory,
to avoid such ambiguity.
It's still a bottomless pit -- ask Brett, who implemented the Python
strptime <wink>.


True, I did overlook timezones at the time.

On the other hand, that's because *my* use cases for "simple"
fromstring() behaviour are all involving local time. When
I'm interested in non-local time, I would be happy having
to specify that behaviour in a more complex manner.
OTOH, is that what people really want? For all I know,
rfc822.getdate() or rfc822.getdate_tz() are what's really wanted, or
maybe some DWIM thing like Zope's date guessers.


To each his own, although I think there's a hope here that
for those who might need/want a really simple solution,
95% of people have this in mind (pseudo-code):

class datetime.date:
def fromstring(format, string):
ts = time.mktime(time.strptime(string, format))
return datetime.date.fromtimestamp(ts)

The .fromtimestamp() methods already work only for local
time, and I haven't heard anyone complaining about that
either. (Hmm... haven't been listening either though. :-)

-Peter
Jul 18 '05 #9
Peter Hansen wrote:
Tim Peters wrote:
[Peter Hansen]
I think Skip was intending that the format string be mandatory,
to avoid such ambiguity.

It's still a bottomless pit -- ask Brett, who implemented the Python
strptime <wink>.

True, I did overlook timezones at the time.

On the other hand, that's because *my* use cases for "simple"
fromstring() behaviour are all involving local time. When
I'm interested in non-local time, I would be happy having
to specify that behaviour in a more complex manner.
OTOH, is that what people really want? For all I know,
rfc822.getdate() or rfc822.getdate_tz() are what's really wanted, or
maybe some DWIM thing like Zope's date guessers.

To each his own, although I think there's a hope here that
for those who might need/want a really simple solution,
95% of people have this in mind (pseudo-code):

class datetime.date:
def fromstring(format, string):
ts = time.mktime(time.strptime(string, format))
return datetime.date.fromtimestamp(ts)


Hear, hear, the above would be great!
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Ralph Freshour | last post by:
What's a good way to calculate the number of days between two dates in the following format: 2003-07-15 2003-08-02 I've looked at the PHP date functions but I'm still a bit lost...
6
by: Pete | last post by:
Hi Guys I have a form which must calc the difference between 2 date fields and return the result in a third field. I have the following code but it does not seem to work. Can anyone tell this...
26
by: sgershon | last post by:
Hi. I know this is should be a simple question. I know server-side web-programming, and never needed to use client-side scripting... until now :) I have done so far a little number of scripts...
6
by: Mark Reed | last post by:
Hi Guru's, I have created a database to monitor hours I have worked as our payroll department are so crap. I work nights most of the time but occasionally I have to work on days. Between the hours...
29
by: james | last post by:
I have a problem that at first glance seems not that hard to figure out. But, so far, the answer has escaped me. I have an old database file that has the date(s) stored in it as number of days. An...
2
by: yxq | last post by:
Hello, I found there are some date formats in the email header, for example: Fri, 23 Sep 2005 08:51:56 +0800 Sat, 17 Sep 2005 09:08:07 Wed Oct 19 13:40:23 2005 19 Oct 2005 13:40:23 +0000...
7
by: Gucci | last post by:
<?php /** * check ine year is a leap year, and return the month day array * * @param int $year **the year must bigger than zero** * @return array */ function is_leap_year($year){...
2
by: MLH | last post by:
With a table of holidays and A97's date fn's - how best to count weekends and holidays between two dates? My holiday table has 4 fields. I will be adding records to it each year as info becomes...
6
by: Jeremy Sanders | last post by:
Hi - I need to add support to a program for dates and times. The built-in Python library seems to be okay for many purposes, but what I would like would be Unix epoch style times (seconds relative...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.