473,396 Members | 2,081 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,396 software developers and data experts.

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!

Jun 16 '06 #1
12 5517
co***********@gmail.com writes:
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


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.today(). 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

Jun 16 '06 #2
> 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
No year, right? Are you making the assumption that the year is
the current year?
How would I go about comparing that to a different date?


Once you've got them as dates,
from datetime import date
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:
month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) 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
webpageDateString = "Mar 21"
webMonth, webDay = webpageDateString.split()
month = m[webMonth]
day = int(webDay)
webpageDate = date(date.today().year, month, day)
compareDate = date.today()
compareDate < webpageDate False compareDate > webpageDate True

You can wrap the load in a function, something like
def isNewer(dateString, year = date.today().year): .... monthString, dayString = dateString.split()
.... month = month_numbers[monthString]
.... day = int(dayString)
.... return date.today() < date(year, month, day)

which will allow you to do
isNewer("Jul 1") True isNewer("Apr 1")

False

and the like.

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

-tkc


Jun 16 '06 #3
Ben Finney <bi****************@benfinney.id.au> writes:
co***********@gmail.com writes:
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


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.today(). 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


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.today()
- 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

Jun 16 '06 #4
Tim Chase <py*********@tim.thechases.com> writes:
If you need to map the month-strings back into actual dates, you
can use this dictionary:
>>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m)

for m in range(1,13)])


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

Jun 16 '06 #5
On 16/06/2006 11:23 AM, Ben Finney wrote:
co***********@gmail.com writes:
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
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.today(). 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,


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]
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.


It doesn't.

Jun 16 '06 #6
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?

Jun 16 '06 #7
On 17/06/2006 9:55 AM, co***********@gmail.com wrote:
So when I grab the date of the website, that date is actually a string?
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, ...
How would I got about converting that to a date?


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
Jun 17 '06 #8
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.So
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

Jun 17 '06 #9
> I will try to work through Tim's response. I tried using it
yesterday but I was really confused on what I was doing.


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
import datetime
help(datetime)
help(datetime.date)
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:
dir(datetime.date) or print "\n".join(dir(datetime.date))


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

Jun 17 '06 #10
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:
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


No year, right? Are you making the assumption that the year is
the current year?
How would I go about comparing that to a different date?


Once you've got them as dates,
>>> from datetime import date
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:
>>> month_numbers = dict([(date(2006, m, 1).strftime("%b"), m) 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
>>> webpageDateString = "Mar 21"
>>> webMonth, webDay = webpageDateString.split()
>>> month = m[webMonth]
>>> day = int(webDay)
>>> webpageDate = date(date.today().year, month, day)
>>> compareDate = date.today()
>>> compareDate < webpageDate False >>> compareDate > webpageDate True

You can wrap the load in a function, something like
>>> def isNewer(dateString, year = date.today().year): ... monthString, dayString = dateString.split()
... month = month_numbers[monthString]
... day = int(dayString)
... return date.today() < date(year, month, day)

which will allow you to do
>>> isNewer("Jul 1") True >>> isNewer("Apr 1")

False

and the like.

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

-tkc


Jun 19 '06 #11
> 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.


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

Jun 19 '06 #12
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:
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.


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


Jun 20 '06 #13

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

Similar topics

4
by: F | last post by:
Hi I have posted the question few days back about problem in inserting the dates in SQL server and thankful to them who replied. That was solved and this is a nice solution....
2
by: Duppypog | last post by:
I'm trying to compare a date stored in a database with today's date using an If statement, but it's not returning true. Example, value in database is 11/5/2003 with today being 11/6/2003. Can...
2
by: Philip Townsend | last post by:
I am having difficulty with a simple routine as follows: public static bool VerifyExpirationDate(DateTime date) { if(date>=DateTime.Now)return true; else return false; } The problem is that...
2
by: Manny Chohan | last post by:
Hi, i have two datetime values in format 11/22/04 9:00 AM and 11/22/04 9:30 AM. How can i compare dates .net c# or if there is any other way such as Javascript. Thanks Manny
13
by: **Developer** | last post by:
I need to sort the columns of a ListView. Some columns contain dates and others contain integers. What I did once before is in the Compare method I tried date and if that failed I did...
2
by: cyber100 | last post by:
Is there an easy way to calculate how many days between two dates.. i have two dates and want to work out how many days between them, i have a static date and was getting todays date then working...
4
by: cheryl | last post by:
I am using the PHP.MYSQL and Apache server application in developing my website. I have problem in comparing dates. Website has room reservation, the user will check first the room availability. The...
2
by: dantebothermy | last post by:
Is there a simple way to subtract the time from a datetime field, so when I compare dates, I'm always comparing the dates at 12:00 am? I'd really prefer not to convert all my dates to strings. ...
4
by: jupi13 | last post by:
i have this code..i don't know what where is the error in this one..it says data type mismatch..... Dim Mydate As Date Dim MydateString As String MydateString = "Text1.Text" Mydate =...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.