473,721 Members | 2,186 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

comparing datetime with date

I was very surprised to discover that
import datetime
x = datetime.date(2 004, 9, 14)
y = datetime.dateti me(2004, 9, 14, 6, 43, 15)
print x == y

True

How can these two objects be considered equal? Is there a *general* way
to test for date != datetime as well as 4.5 != 4.6?

Donnal Walter
Arkansas Children's Hospital
Jul 18 '05 #1
16 13127
Donnal Walter wrote:
I was very surprised to discover that
>>> import datetime
>>> x = datetime.date(2 004, 9, 14)
>>> y = datetime.dateti me(2004, 9, 14, 6, 43, 15)
>>> print x == y
True

How can these two objects be considered equal?


Guessing:

In http://docs.python.org/lib/datetime-datetime.html
it says this """Note: In order to stop comparison from falling back to
the default scheme of comparing object addresses, datetime comparison
normally raises TypeError if the other comparand isn't also a datetime
object. However, NotImplemented is returned instead if the other
comparand has a timetuple attribute. This hook gives other kinds of date
objects a chance at implementing mixed-type comparison. """
(the docs for the date class say the same).

I suspect this means simply that datetime.date *does* use this
behaviour to provide a mixed-type comparison that makes sense,
to _it_.
Is there a *general* way
to test for date != datetime as well as 4.5 != 4.6?


Couldn't say, sorry.

-Peter
Jul 18 '05 #2
Donnal Walter wrote:
I was very surprised to discover that
>>> import datetime
>>> x = datetime.date(2 004, 9, 14)
>>> y = datetime.dateti me(2004, 9, 14, 6, 43, 15)
>>> print x == y
True


I think thats perfectly legal - a date object should care only about if the
object it is compared to contains some sort of valid date information, and
restrict its comparision to that.

The matter is that you try to compare two different things here - so its up
to the implementation if how it deals with this, as there is no canonical
way to compare two things that aren't even structural equivalent.

The current implementation chose one way to do it - and thats as good as any
other one could think of, and certainly has some convenience advantage on
its side.
How can these two objects be considered equal? Is there a *general* way
to test for date != datetime as well as 4.5 != 4.6?


Try making a datetime-object from your date, with zeros for the time part -
then you'll get what you want.

--
Regards,

Diez B. Roggisch
Jul 18 '05 #3
Diez B. Roggisch wrote:
Donnal Walter wrote:
How can these two objects be considered equal? Is there a *general* way
to test for date != datetime as well as 4.5 != 4.6?


Try making a datetime-object from your date, with zeros for the time part -
then you'll get what you want.


While trying to provide my first answer, I thought of suggesting
this, but there doesn't appear to be a simple way of doing it.
It looked like the following was the best I could do (where 'x'
is a datetime.date object):

z = datetime.dateti me(x.year, x.month, x.day)

I just found timetuple(), which means this could be written
in the awful form:

z = datetime.dateti me(*x.timetuple ()[:3])

but that's hardly better, and definitely more inscrutable.

To answer Donnal's question above, however, it appears this
might be a reasonable approach:
x.timetuple() == y.timetuple()

False

Not sure there's a better approach readily available.

-Peter
Jul 18 '05 #4
[Diez B. Roggisch]
Try making a datetime-object from your date, with zeros for the time part -
then you'll get what you want.
[Peter Hansen]
While trying to provide my first answer, I thought of suggesting
this, but there doesn't appear to be a simple way of doing it.


datetime.dateti me has a class constructor for building a datetime out
of a date and a time, so this can be done via a simple one-liner:
import datetime
t = datetime.date.t oday()
t datetime.date(2 004, 9, 14) datetime.dateti me.combine(t, datetime.time() ) datetime.dateti me(2004, 9, 14, 0, 0)

Jul 18 '05 #5
Peter Hansen wrote:
Diez B. Roggisch wrote:
Donnal Walter wrote:
How can these two objects be considered equal? Is there a *general* way
to test for date != datetime as well as 4.5 != 4.6?

Try making a datetime-object from your date, with zeros for the time
part -
then you'll get what you want.

While trying to provide my first answer, I thought of suggesting
this, but there doesn't appear to be a simple way of doing it.
It looked like the following was the best I could do (where 'x'
is a datetime.date object):

z = datetime.dateti me(x.year, x.month, x.day)

I just found timetuple(), which means this could be written
in the awful form:

z = datetime.dateti me(*x.timetuple ()[:3])

but that's hardly better, and definitely more inscrutable.

To answer Donnal's question above, however, it appears this
might be a reasonable approach:
>>> x.timetuple() == y.timetuple()

False

Not sure there's a better approach readily available.

-Peter


Thanks for the suggestions. I have decided *not* to store date/datetime
objects, but rather store the corresponding time tuples: 3-tuple for
date only, and 5- or 6-tuple for date and time, depending on whether or
not seconds are given). Then the following method notifies observers if
a simple date is changed to the date with time (just like number changes
and string changes).

def set(self, value):
if value != self._state: # now this works!
self._state = value
self.notify_obs ervers(self)

This means, of course, that if an observer wants to calculate a
TimeDelta, the corresponding datetimes have to be constructed, but I
don't think this is too inefficient.

time1 = datetime.dateti me(*time1.get() ) # 3-, 5-, or 6-tuple
time2 = datetime.dateti me(*time2.get() )
tdelta = time2 - time1

The observer object (and user) would need to understand the loss of
precision when times are not actually given, but at least the relevant
methods work regardless.

Thanks again,

Donnal Walter
Arkansas Children's Hospital
Jul 18 '05 #6
This is very interesting because if you continue further and coerce both to
strings you get:
print str(y) == str(y) True str(y) '2004-09-14 06:43:15' str(x) '2004-09-14'
Even though there string values are different they still match?

If we perform a CRC (Cyclic Redundancy Check) i.e compute a one way hash:

import binascii crc_x = binascii.crc32( str(x))
crc_y = binascii.crc32( str(y))
print crc_x == crc_y
False

So this confirms that there values do differ yet a comparision using ==
returns True?

All i can assume is that when a Date / DateTime comparision is made the
'lowest denominator' i.e Date is used but I may be very wrong

Will watch this thread closely

"Donnal Walter" <do****@donnal. net> wrote in message
news:ma******** *************** *************** @python.org...
I was very surprised to discover that
import datetime
x = datetime.date(2 004, 9, 14)
y = datetime.dateti me(2004, 9, 14, 6, 43, 15)
print x == y

True

How can these two objects be considered equal? Is there a *general* way to
test for date != datetime as well as 4.5 != 4.6?

Donnal Walter
Arkansas Children's Hospital

Jul 18 '05 #7
On Wed, 15 Sep 2004 09:24:03 +1000,
Graeme Matthew <gr************ @contrado.com.a u> wrote:
This is very interesting because if you continue further and coerce both to
strings you get:
print str(y) == str(y) True


Of course if you actually do:
print str(x) == str(y) False


str(y) '2004-09-14 06:43:15' str(x) '2004-09-14'


Even though there string values are different they still match?


No, they only matched becuase you compared y with y :)
--
Sam Holden
Jul 18 '05 #8
On Wed, 15 Sep 2004 09:24:03 +1000 Graeme wrote:
This is very interesting because if you continue further and coerce both
to strings you get:
print str(y) == str(y) of course: ^ ^ :^)
True Even though there string values are different they still match? today = datetime.date(2 004,9,14)
yesterday = datetime.date(2 004,9,13)
now = datetime.dateti me(2004,9,14,20 ,0)
now == today True now == yesterday False
Looks like date and datetime have 3 arguments and minimum 3 args
respectively, so the comparison appears to simply use the minimum data
available... when given more data to compare, we get:
minute_ago = datetime.dateti me(2004,9,14,19 ,59)
minute_ago == now

False

All i can assume is that when a Date / DateTime comparision is made the
'lowest denominator' i.e Date is used but I may be very wrong
I agree...
Will watch this thread closely

Jul 18 '05 #9
yes it was late, apologies therefore a simple way to solve this problem
would be:

str(x) == str(y)

:=-)

"Sam Holden" <sh*****@flexal .cs.usyd.edu.au > wrote in message
news:slrnckf3e5 .ptn.sh*****@fl exal.cs.usyd.ed u.au...
On Wed, 15 Sep 2004 09:24:03 +1000,
Graeme Matthew <gr************ @contrado.com.a u> wrote:
This is very interesting because if you continue further and coerce both
to
strings you get:
> print str(y) == str(y)

True


Of course if you actually do:
> print str(x) == str(y)

False


> str(y)

'2004-09-14 06:43:15'
> str(x)

'2004-09-14'
>


Even though there string values are different they still match?


No, they only matched becuase you compared y with y :)
--
Sam Holden

Jul 18 '05 #10

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

Similar topics

2
1837
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 strPassword = '" & hshPW & "'"
2
3343
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
5
1169
by: JIM.H. | last post by:
Hello, Since I am learning C# now, I might have a simple question, I know my datarow dr keeps datatime and I need to compare it if it is current date, if not how many days ago? How should I compare date and find how many day difference? Thanks, Jim.
3
270
by: Nathan | last post by:
Hi, I can't seem to this part of my function to work: Private Function TotalHours(ByVal InTime As Date, ByVal OutTime As Date) As Double Msgbox(InTime.Tostring) Select Case InTime Case #12:00:00 AM# To #8:00:59 AM# etc., etc.
4
2683
by: richardkreidl | last post by:
How would I check to see if the current time(military format) is greater then 07:30AM and the day of the week is Monday-Friday. Pseudo code: If Current_Time > 07:30AM and Current_Day = Monday or Current_Day = Tuesday _ or Current_Day = Wednesday or Current_Day = Thursday or Current_Day = Friday then
12
5560
by: colincolehour | last post by:
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...
2
1402
by: Bob | last post by:
Hi, I have a wrong result when testing today against a date fetched from a table in excel. The value in excel is: 14/12/2006 (european format). When today is after that value in excel, the message "time is over" must appear, otherwise nothing. My problem is that the message appear already when today = that value. Any idea why?
2
1848
by: =?Utf-8?B?QWxoYW1icmEgRWlkb3MgS2lxdWVuZXQ=?= | last post by:
Hi mister, I have an object with two properties, of type DateTime? (Nullable). Which is the best way for comparing ? The value of datetime can be null, and another value cannot be null, or two values are null, or two values aren't null. if (tarea.Fcprioridad < tarea.Fcentrega)
3
2705
by: Anil Gupte | last post by:
I am using the followig code: SqlConnection con = new SqlConnection(strcon); con.Open(); string strSelect = "Select PaidUntil from Users where username='" + un + "'"; SqlCommand cmd = new SqlCommand(strSelect, con); SqlDataReader dr; dr = cmd.ExecuteReader(); dr.Read();
0
9367
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, 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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9131
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9064
tracyyun
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8007
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5981
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4484
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3189
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2130
bsmnconsultancy
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.