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! 12 5529 co***********@g mail.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.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
> 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
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
False compareDate > webpageDate
True
You can wrap the load in a function, something like
def isNewer(dateStr ing, year = date.today().ye ar):
.... 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
isNewer("Jul 1")
True isNewer("Apr 1")
False
and the like.
There's plenty of good stuff in the datetime module.
-tkc
Ben Finney <bi************ ****@benfinney. id.au> writes: co***********@g mail.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.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
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
Tim Chase <py*********@ti m.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
On 16/06/2006 11:23 AM, Ben Finney wrote: co***********@g mail.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.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,
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.
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?
On 17/06/2006 9:55 AM, co***********@g mail.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
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
> 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.d ate)
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.da te)
or print "\n".join(dir(d atetime.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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
http://www.aspfaq.com/show.asp?id=2023
Now I am facing another problem.
I have to get data between two dates. That dates user has to provide and in
|
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 someone spot the problem?
Thanks,
Lynnette
Here's the code:
sSQL = "Select PWExpire FROM tblUsers where strUserName = '" & stUser & "'
AND...
|
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 when today's date is passed in, the method returns
false. Any ideas? Thanks!
|
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
|
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 Integer.
Seems kinda not nice - is there a better way?
Thanks
| |
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 out for each what the day of the year was and subtracting the two, this worked fine until the new year.. now i have dates from 2006 and todays date of...
|
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 user will input dates using the combo box like cboyear,cboday and cbomonth. What SQL statement or quey should I write to compare it to the database....
|
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.
Thanks,
Dante
|
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 = CDate(MydateString) ''it is highlighted in this line..
txtActCode = Mydate
i don't know what's wrong with this one..
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language...
| |
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it. ...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...
| |