In Python: `date` vs `datetime` object



This content originally appeared on DEV Community and was authored by DoriDoro

In Python, date and datetime are classes provided by the datetime module for handling dates and times.

  1. Difference Between date and datetime Objects:

date Object:
Represents a calendar date (year, month, and day) without any time-of-day information.
Example:

from datetime import date

d = date.today()  # Gets the current date
print(d)  # Output will be something like 2023-10-04

datetime Object:
Represents a specific moment in time, including both the date and the time (year, month, day, hour, minute, second, microsecond).
Example:

from datetime import datetime

dt = datetime.now()  # Gets the current date and time
print(dt)  # Output will be something like 2023-10-04 15:06:00.123456

In summary, use date to represent dates without time, and datetime to represent a specific point in time inclusive of both date and time.

  1. Checking Object Type: To check the type of an object, you can use the built-in type() function or the isinstance() function.

Using type():

from datetime import date, datetime

some_date = date.today()
some_datetime = datetime.now()

print(type(some_date))      # <class 'datetime.date'>
print(type(some_datetime))  # <class 'datetime.datetime'>

Using isinstance():

from datetime import date, datetime

some_date = date.today()
some_datetime = datetime.now()

print(isinstance(some_date, date))         # True
print(isinstance(some_date, datetime))     # False
print(isinstance(some_datetime, date))     # False
print(isinstance(some_datetime, datetime)) # True

Using isinstance() is usually preferred, especially when dealing with inheritance, because it considers subclasses and provides a more flexible and safe way to check types.

To apply this in the context you provided:

from datetime import date, datetime

# Assuming period.upper is the attribute you want to check
if isinstance(period.upper, date) and not isinstance(period.upper, datetime):
    current_date = date.today()
else:
    current_date = datetime.now()

This way, you ensure that current_date uses date.today() if period.upper is a date object, and timezone.now() otherwise (if it was a datetime object).


This content originally appeared on DEV Community and was authored by DoriDoro