To check if a variable is a datetime, you can use the type() function and check if the variable is of type date or datetime.

from datetime import datetime, date

datetime_var = datetime.now()
date_var = datetime_var.date()

def checkDatetime(var):
    return type(var) == datetime

def checkDate(var):
    return type(var) == date

print(checkDatetime(datetime_var))
print(checkDate(datetime_var))
print(checkDatetime(date_var))
print(checkDate(date_var))

#Output:
True
False
False
True

When working with different types of variables in Python, the ability to check the type of the variables easily is valuable.

One such case is if you want to check if a variable is a date or datetime in your Python code.

To check if a variable is of type date or datetime, you can use the type() function.

type() returns the class type of the argument passed.

If type() returns datetime or date, then we can conclude the variable is a datetime or date.

Below are some examples showing you how to check if a variable is a date or datetime in Python.

from datetime import datetime, date

datetime_var = datetime.now()
date_var = datetime_var.date()

def checkDatetime(var):
    return type(var) == datetime

def checkDate(var):
    return type(var) == date

print(checkDatetime(datetime_var))
print(checkDate(datetime_var))
print(checkDatetime(date_var))
print(checkDate(date_var))

#Output:
True
False
False
True

Using isinstance() to Check if Variable is date in Python

One other way you can check if a variable is of type date is with the isinstance() function.

isinstance() checks to see if a variable is an instance of the class passed.

Below is an example showing you how to use isinstance() in Python to check if a variable is datetime.date.

Note, you’ll see below that when we pass the datetime variable, we receive True from both checkDatetime and checkDate.

Therefore, we can only check if a variable is of type date in this case because datetime is a subclass of date.

from datetime import datetime, date

datetime_var = datetime.now()
date_var = datetime_var.date()

def checkDatetime(var):
    return isinstance(var, datetime)

def checkDate(var):
    return isinstance(var, date)

print(checkDatetime(datetime_var))
print(checkDate(datetime_var))
print(checkDatetime(date_var))
print(checkDate(date_var))

#Output:
True
True
False
True

Hopefully this article has been useful for you to check if a variable is a datetime or date in Python.

Categorized in:

Python,

Last Update: February 26, 2024