matel
matel

Reputation: 485

python datetime operation

I have the following error, can someone please explain the difference between datetime.datetime and datetime.date?

TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'

Upvotes: 1

Views: 548

Answers (2)

Hannele
Hannele

Reputation: 9666

date is just a date (year, month, day), while datetime also includes a time (year, month, day, hour, minutes, seconds, milliseconds).

You can't compare the two directly, because you need to explicitly specify how to deal with the time part. Do you ignore the time part completely, or do you select some arbitrary time to compare with when necessary (usually midnight)? This choice depends on which is the most appropriate to your situation, and really, only you can determine that.

In more concrete terms, you must either promote the date to a datetime, or demote the datetime to a date. Given dt as the datetime, and d as the date, the latter is a little easier (and generally makes more sense - you can just call dt.date()), but the former is also not difficult (datetime.datetime(d.year, d.month, d.day)).

In your code, it would either look like dt.date() - d or dt - datetime.datetime(d.year, d.month, d.day).

And note, that this will return a datetime.timedelta object, which is another slightly different animal - it doesn't represent a specific point in time, only the difference between two points (i.e, you couldn't use it as a date on a calendar).

Upvotes: 1

user4815162342
user4815162342

Reputation: 154906

As the name implies, a datetime includes information about both the date and time, while a date is only a date. This is why subtracting two datetimes is allowed and returns a timedelta (the time difference between two instants), but subtracting a datetime and a date is not — since date refers to a whole day, it is unclear to what part of that day you want to calculate the distance to.

To fix the error, you must specify which point in the day your refers to. For example, to have it refer to the midnight at the beginning of the date, replace dt - d with dt - datetime.datetime(d.year, d.month, d.day).

Upvotes: 2

Related Questions