disc0dancer
disc0dancer

Reputation: 9365

Why is there a date class in python

Doesn't datetime cover all that date can do? I haven't read all the documentation, but so far I always find myself using datetime. Even in Django - datetime model fields are always more useful (at least for me). You don't have to use the hours if you don't want to, but if you decide that you do, you can.

Javascript seems to manage fine with only one date class.

Can you give me an example case where date is preferred to datetime?

Upvotes: 2

Views: 390

Answers (3)

Vishal1949
Vishal1949

Reputation: 9

datetime is a the same as the types date and time. The only thing better is that it takes less space than date does.

Upvotes: -1

Darren Yin
Darren Yin

Reputation: 648

Certain concepts may be easier to understand as dates rather than datetimes. For example, birthdays, paydays, and due dates all could potentially be datetimes, but they may be far better expressed as simple dates. Expressing these as datetimes could lead to confusion/ambiguity down the road.

First of all, future maintainers of your code may think that you're already using dates. Then they could be surprised by how the comparison operations behave, as two apparently identical birthdays may not be "equal."

Also, even if they know that a birthday is represented as a datetime, it's not immediately obvious what the time will be. It might be reasonable for the time to always be the exact time of birth in UTC. But then there may have to be considerations when the data you get from your users is incomplete, and you default the time to be midnight UTC. And then if you do that, you no longer know if a birthday with a midnight UTC time was auto-filled, or if that was actually user provided data.

And otherwise, if you just assign a placeholder midnight UTC time to each datetime, the meaning of the associated time field of every birthday may still not be immediately clear to someone new to the codebase. Someone who isn't aware of this convention could change the time field of one of these datetimes, and that could then lead to functionality breaking very invisibly. If it had just been a date, that problem would have been averted.

tl,dr: date exists to make it easier for developers to use the "right tool for the job."

Upvotes: 4

GaretJax
GaretJax

Reputation: 7780

When you only need the date component and can do without the time.

datetime is a composition of the date and time types, so, yes, datetime does all what date does (and does also all what time does).

Choosing one instead of the other is thus pretty simple: if you want to record only a date, use date; if you need to be more specific and track also the time of a given event, then use a date time object. The same applies to the time object, in case an event needs only to be bound to a given time and the date is not relevant.

Upvotes: 4

Related Questions