Need Help comparing dates

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • colincolehour@gmail.com

    #1

    Need Help comparing dates

    I am new to Python and am working on my first program. I am trying to
    compare a date I found on a website to todays date. The problem I have
    is the website only shows 3 letter month name and the date.
    Example: Jun 15

    How would I go about comparing that to a different date? The purpose of
    my program is to load a webpage and see if the content on the front
    page is fresh or stale as in older than a few days. Any help in the
    right direction would be great!

  • Ben Finney

    #2
    Re: Need Help comparing dates

    colincolehour@g mail.com writes:
    [color=blue]
    > I am new to Python and am working on my first program. I am trying
    > to compare a date I found on a website to todays date. The problem I
    > have is the website only shows 3 letter month name and the date.
    > Example: Jun 15[/color]

    The 'datetime' module in the standard library will do the job of
    creating date objects that can be compared.

    <URL:http://docs.python.org/lib/module-datetime>

    Construct a date from arbitrary values with datetime.date() , get the
    current date with datetime.date.t oday(). The objects returned by those
    functions can be compared directly.

    As for how to get from a string representation to a date object,
    you're now talking about parsing strings to extract date/time
    information. This isn't provided in the standard library, largely
    because there's no "one obvious way to do it". An existing PEP
    proposing adding such functionality has since been withdrawn:

    <URL:http://www.python.org/dev/peps/pep-0321/>

    Parsing datetime values from strings is fuzzy and prone to lots of
    assumptions and errors, so the programmer must choose their own set of
    assumptions. One popular implementation of a specific set of
    assumptions is the egenix 'mxDateTime' module.

    <URL:http://www.egenix.com/files/python/mxDateTime.html >

    That module predates (and was largely an inspiration for) the standard
    library 'datetime' module; however, I don't know if the egenix module
    uses objects that can be used with those from the standard library.

    --
    \ "There is no reason anyone would want a computer in their |
    `\ home." -- Ken Olson, president, chairman and founder of |
    _o__) Digital Equipment Corp., 1977 |
    Ben Finney

    Comment

    • Tim Chase

      #3
      Re: Need Help comparing dates

      > I am new to Python and am working on my first program. I am trying to[color=blue]
      > compare a date I found on a website to todays date. The problem I have
      > is the website only shows 3 letter month name and the date.
      > Example: Jun 15[/color]

      No year, right? Are you making the assumption that the year is
      the current year?
      [color=blue]
      > How would I go about comparing that to a different date?[/color]

      Once you've got them as dates,
      [color=blue][color=green][color=darkred]
      >>> from datetime import date[/color][/color][/color]

      you can just compare them as you would any other comparable items.

      If you need to map the month-strings back into actual dates, you
      can use this dictionary:
      [color=blue][color=green][color=darkred]
      >>> month_numbers = dict([(date(2006, m, 1).strftime("%b "), m)[/color][/color][/color]
      for m in range(1,13)])

      It happens to be locale specific, so you might have to tinker a
      bit if you're mapping comes out differently from what the website
      uses. I also made the assumption the case was the same (rather
      than trying to normalize to upper/lower case)

      Then, you can use
      [color=blue][color=green][color=darkred]
      >>> webpageDateStri ng = "Mar 21"
      >>> webMonth, webDay = webpageDateStri ng.split()
      >>> month = m[webMonth]
      >>> day = int(webDay)
      >>> webpageDate = date(date.today ().year, month, day)
      >>> compareDate = date.today()
      >>> compareDate < webpageDate[/color][/color][/color]
      False[color=blue][color=green][color=darkred]
      >>> compareDate > webpageDate[/color][/color][/color]
      True

      You can wrap the load in a function, something like
      [color=blue][color=green][color=darkred]
      >>> def isNewer(dateStr ing, year = date.today().ye ar):[/color][/color][/color]
      .... monthString, dayString = dateString.spli t()
      .... month = month_numbers[monthString]
      .... day = int(dayString)
      .... return date.today() < date(year, month, day)

      which will allow you to do
      [color=blue][color=green][color=darkred]
      >>> isNewer("Jul 1")[/color][/color][/color]
      True[color=blue][color=green][color=darkred]
      >>> isNewer("Apr 1")[/color][/color][/color]
      False

      and the like.

      There's plenty of good stuff in the datetime module.

      -tkc




      Comment

      • Ben Finney

        #4
        Re: Need Help comparing dates

        Ben Finney <bignose+hate s-spam@benfinney. id.au> writes:
        [color=blue]
        > colincolehour@g mail.com writes:[color=green]
        > > I am new to Python and am working on my first program. I am trying
        > > to compare a date I found on a website to todays date. The problem I
        > > have is the website only shows 3 letter month name and the date.
        > > Example: Jun 15[/color]
        >
        > The 'datetime' module in the standard library will do the job of
        > creating date objects that can be compared.
        >
        > <URL:http://docs.python.org/lib/module-datetime>
        >
        > Construct a date from arbitrary values with datetime.date() , get the
        > current date with datetime.date.t oday(). The objects returned by those
        > functions can be compared directly.
        >
        > As for how to get from a string representation to a date object,
        > you're now talking about parsing strings to extract date/time
        > information. This isn't provided in the standard library[/color]

        As soon as I sent this, I remembered that the standard library *does*
        provide datetime parsing:

        <URL:http://docs.python.org/lib/module-time#l2h-1956>

        So your task now consists of:

        - get a date object of today's date using datetime.date.t oday()
        - define a format for parsing a string date
        - get a struct_time object from time.strptime() feeding it the
        string and the format
        - make any assumptions about missing pieces of the date (e.g. the
        year)
        - get a date object by feeding values to datetime.date()
        - compare the two date objects

        --
        \ "Hey Homer! You're late for English!" "Pff! English, who needs |
        `\ that? I'm never going to England!" -- Barney & Homer, _The |
        _o__) Simpsons_ |
        Ben Finney

        Comment

        • Ben Finney

          #5
          Re: Need Help comparing dates

          Tim Chase <python.list@ti m.thechases.com > writes:
          [color=blue]
          > If you need to map the month-strings back into actual dates, you
          > can use this dictionary:
          >[color=green][color=darkred]
          > >>> month_numbers = dict([(date(2006, m, 1).strftime("%b "), m)[/color][/color]
          > for m in range(1,13)])[/color]

          Or you can just use the same format codes to specify that
          time.strptime() should do the parsing for you. (Which I remembered too
          late for my initial reply.)

          --
          \ "War is God's way of teaching geography to Americans." -- |
          `\ Ambrose Bierce |
          _o__) |
          Ben Finney

          Comment

          • John Machin

            #6
            Re: Need Help comparing dates

            On 16/06/2006 11:23 AM, Ben Finney wrote:[color=blue]
            > colincolehour@g mail.com writes:
            >[color=green]
            >> I am new to Python and am working on my first program. I am trying
            >> to compare a date I found on a website to todays date. The problem I
            >> have is the website only shows 3 letter month name and the date.
            >> Example: Jun 15[/color]
            >
            > The 'datetime' module in the standard library will do the job of
            > creating date objects that can be compared.
            >
            > <URL:http://docs.python.org/lib/module-datetime>
            >
            > Construct a date from arbitrary values with datetime.date() , get the
            > current date with datetime.date.t oday(). The objects returned by those
            > functions can be compared directly.
            >
            > As for how to get from a string representation to a date object,
            > you're now talking about parsing strings to extract date/time
            > information. This isn't provided in the standard library,[/color]

            time.strptime() doesn't do "parsing strings to extract date/time
            information"?

            It appears to me to do a reasonably tolerant job on the OP's spec i.e.
            month abbreviation and a day number:

            |>> import time
            |>> time.strptime(' Jun 15', '%b %d')
            (1900, 6, 15, 0, 0, 0, 4, 166, -1)
            |>> time.strptime(' dec 9', '%b %d')
            (1900, 12, 9, 0, 0, 0, 4, 152, -1)

            The OP should be able to use that to get the month and the day. The year
            of the web page date will need some guessing (e.g. is within the last
            year) and not even Python has a crystal ball :-)

            BTW, datetime has grown a strptime in version 2.5.


            [snip][color=blue]
            >
            > That module predates (and was largely an inspiration for) the standard
            > library 'datetime' module; however, I don't know if the egenix module
            > uses objects that can be used with those from the standard library.[/color]

            It doesn't.

            Comment

            • colincolehour@gmail.com

              #7
              Re: Need Help comparing dates

              So when I grab the date of the website, that date is actually a string?

              How would I got about converting that to a date?

              Comment

              • John Machin

                #8
                Re: Need Help comparing dates

                On 17/06/2006 9:55 AM, colincolehour@g mail.com wrote:[color=blue]
                > So when I grab the date of the website, that date is actually a string?[/color]

                Yes. Anything you grab off a website (or read from a file) will be held
                in a string. Typically you would then need to convert it (or parts of
                it) to some other type(s) e.g. int, float, date, ...[color=blue]
                >
                > How would I got about converting that to a date?[/color]

                By following the instructions you have already been given. The response
                by Tim Chase gives you a stir-by-stir recipe.
                ===
                You said "I am new to Python and am working on my first program". Here
                are some diagnostic questions the answers to which should enable us to
                prescribe some more help for you: In what other computer language(s)
                have you written programs? What book or tutorial are you using to learn
                Python? Have you worked through the book/tutorial's examples/exercises
                before starting "my first program"?

                Cheers,
                John

                Comment

                • colincolehour@gmail.com

                  #9
                  Re: Need Help comparing dates

                  Thanks for the reply, the book I'm actually using is Python Programming
                  for the absolute beginner. The book has been good to pick up basic
                  things but it doesn't cover time or dates as far as I can tell. As for
                  previous programming experience, I have had some lite introductions to
                  C & C++ about 6 years ago but I never went past the introductions.S o
                  far "my first program" has been written from snippets from many
                  different websites.

                  Also i'm using ActiveState Active Python 2.4 on a Windows XP machine.

                  I will try to work through Tim's response. I tried using it yesterday
                  but I was really confused on what I was doing.

                  Colin

                  Comment

                  • Tim Chase

                    #10
                    Re: Need Help comparing dates

                    > I will try to work through Tim's response. I tried using it[color=blue]
                    > yesterday but I was really confused on what I was doing.[/color]

                    I'll put my plug in for entering the code directly at the shell
                    prompt while you're trying to grok new code or toy with an idea.
                    It makes it much easier to see what is going on as you enter
                    it. You can ask for any variables' value at any time. It's a
                    small pain when you're entering some nested code, and biff up on
                    the interior of it (throwing an exception, and having to restart
                    the function-definition/loop/class-definition statement all
                    over), but it certainly has its advantages for learning the language.

                    On top of that, you can usually ask for help on any object, so if
                    you wanted to know about the datetime module or the date object
                    in the datetime module, you can just use
                    [color=blue][color=green][color=darkred]
                    >>> import datetime
                    >>> help(datetime)
                    >>> help(datetime.d ate)[/color][/color][/color]

                    which will give you all sorts of documentation on a date object.
                    I'm also partial to learning about what methods the object
                    exposes via the dir() function:
                    [color=blue][color=green][color=darkred]
                    >>> dir(datetime.da te)[/color][/color][/color]
                    or[color=blue][color=green][color=darkred]
                    >>> print "\n".join(dir(d atetime.date))[/color][/color][/color]

                    IMHO, help() and dir() at the command-line combine to make one of
                    Python's best selling points...ease of learning. I understand
                    Perl and Ruby might have something similar, but I've never liked
                    their idioms. Java/C/C++, you have the edit/compile/run cycle,
                    so if you just want to explore some simple code ideas, you've got
                    a 3-step process, not just a simple "try it out right here and
                    now" method.

                    I even stopped using "bc" as my command-line calculator,
                    preferring the power of command-line python. :)

                    Just a few thoughts on what made learning python easier for me.

                    Again, if you have questions, and can't figure out the answers by
                    stepping through the code in the command shell (or some
                    strategically placed print statements), this is certainly the
                    forum for asking those questions. It's full of smart and helpful
                    folks.

                    -tkc





                    Comment

                    • colincolehour@gmail.com

                      #11
                      Re: Need Help comparing dates

                      I kept getting a Python error for the following line:

                      month = m[webMonth]


                      I changed it to month = month_numbers[webMonth]

                      and that did the trick.


                      Tim Chase wrote:[color=blue][color=green]
                      > > I am new to Python and am working on my first program. I am trying to
                      > > compare a date I found on a website to todays date. The problem I have
                      > > is the website only shows 3 letter month name and the date.
                      > > Example: Jun 15[/color]
                      >
                      > No year, right? Are you making the assumption that the year is
                      > the current year?
                      >[color=green]
                      > > How would I go about comparing that to a different date?[/color]
                      >
                      > Once you've got them as dates,
                      >[color=green][color=darkred]
                      > >>> from datetime import date[/color][/color]
                      >
                      > you can just compare them as you would any other comparable items.
                      >
                      > If you need to map the month-strings back into actual dates, you
                      > can use this dictionary:
                      >[color=green][color=darkred]
                      > >>> month_numbers = dict([(date(2006, m, 1).strftime("%b "), m)[/color][/color]
                      > for m in range(1,13)])
                      >
                      > It happens to be locale specific, so you might have to tinker a
                      > bit if you're mapping comes out differently from what the website
                      > uses. I also made the assumption the case was the same (rather
                      > than trying to normalize to upper/lower case)
                      >
                      > Then, you can use
                      >[color=green][color=darkred]
                      > >>> webpageDateStri ng = "Mar 21"
                      > >>> webMonth, webDay = webpageDateStri ng.split()
                      > >>> month = m[webMonth]
                      > >>> day = int(webDay)
                      > >>> webpageDate = date(date.today ().year, month, day)
                      > >>> compareDate = date.today()
                      > >>> compareDate < webpageDate[/color][/color]
                      > False[color=green][color=darkred]
                      > >>> compareDate > webpageDate[/color][/color]
                      > True
                      >
                      > You can wrap the load in a function, something like
                      >[color=green][color=darkred]
                      > >>> def isNewer(dateStr ing, year = date.today().ye ar):[/color][/color]
                      > ... monthString, dayString = dateString.spli t()
                      > ... month = month_numbers[monthString]
                      > ... day = int(dayString)
                      > ... return date.today() < date(year, month, day)
                      >
                      > which will allow you to do
                      >[color=green][color=darkred]
                      > >>> isNewer("Jul 1")[/color][/color]
                      > True[color=green][color=darkred]
                      > >>> isNewer("Apr 1")[/color][/color]
                      > False
                      >
                      > and the like.
                      >
                      > There's plenty of good stuff in the datetime module.
                      >
                      > -tkc[/color]

                      Comment

                      • Tim Chase

                        #12
                        Re: Need Help comparing dates

                        > I kept getting a Python error for the following line:[color=blue]
                        >
                        > month = m[webMonth]
                        >
                        > I changed it to month = month_numbers[webMonth]
                        >
                        > and that did the trick.[/color]

                        Sorry for the confusion. Often when I'm testing these things,
                        I'll be lazy and create an alias to save me the typing. In this
                        case, I had aliased the month_numbers mapping to "m":
                        [color=blue][color=green][color=darkred]
                        >>> m = month_numbers[/color][/color][/color]

                        and it slipped into my pasted answer email. You correctly fixed
                        the problem. The purpose of the mapping is simply to resolve the
                        month name to the month number so that the month number can be
                        used. Depending on how predictable the website's date string
                        will be, you can use

                        month_numbers = dict([(date(2006, m, 1).strftime("%b ").upper(),
                        m) for m in range(1,13)])

                        and then use

                        month = month_numbers[webMonth.upper( )]

                        or

                        month = month_numbers[webMonth[0:3].upper()]

                        depending on whether the website might return full month names or
                        not.

                        -tkc





                        Comment

                        • colincolehour@gmail.com

                          #13
                          Re: Need Help comparing dates

                          The program works great! It does everything I wanted it to do and now
                          I'm already thinking about ways of making it more useful like emailing
                          me the results of my program.

                          Thanks everyone for the help and advice.

                          Colin

                          Tim Chase wrote:[color=blue][color=green]
                          > > I kept getting a Python error for the following line:
                          > >
                          > > month = m[webMonth]
                          > >
                          > > I changed it to month = month_numbers[webMonth]
                          > >
                          > > and that did the trick.[/color]
                          >
                          > Sorry for the confusion. Often when I'm testing these things,
                          > I'll be lazy and create an alias to save me the typing. In this
                          > case, I had aliased the month_numbers mapping to "m":
                          >
                          > >>> m = month_numbers
                          >
                          > and it slipped into my pasted answer email. You correctly fixed
                          > the problem. The purpose of the mapping is simply to resolve the
                          > month name to the month number so that the month number can be
                          > used. Depending on how predictable the website's date string
                          > will be, you can use
                          >
                          > month_numbers = dict([(date(2006, m, 1).strftime("%b ").upper(),
                          > m) for m in range(1,13)])
                          >
                          > and then use
                          >
                          > month = month_numbers[webMonth.upper( )]
                          >
                          > or
                          >
                          > month = month_numbers[webMonth[0:3].upper()]
                          >
                          > depending on whether the website might return full month names or
                          > not.
                          >
                          > -tkc[/color]

                          Comment

                          Working...