Home > Mobile >  Determine if datetime object is date or datetime
Determine if datetime object is date or datetime

Time:10-30

I am trying to format datetime objects, and I wrote a little function to determine if the datetime object is a date or datetime object. But, nothing I've tried works.

Generating date and date times with datetime.date.today() and datetime.datetime.now() and assigning that to dtDate.

My first attempt was isinstance() :

dtDate = datetime.date.today()
# dtDate = datetime.datetime.now()

if isinstance(dtDate, date) :
        sDate = dtDate.strftime('%x')
    elif isinstance(dtDate, datetime) :
        sDate = dtDate.strfttime('%x %X')

But that triggers regardless of whether it is a date or datetime. If I am more specific, like 'datetime.date' says 'arg 2 must be type or tuple'.

I also tried to detect if the object had the hour field :

if dtDate.hour :
    sDate = dtDate.strftime('%x %X')
else :
    sDate = dtDate.strfttime('%x')

But, that freaks out if the object is purely a date, without an hour attribute.

Even a try/except block has issues :

try :
    if dtDate.hour :
        sDate = dtDate.strftime('%x %X')
except :
    sDate = dtDate.strfttime('%x')

This returns 'datetime.date' object has no attribute 'strfttime' for date objects.

Lastly, I tried to compare types :

if type(dtDate) is datetime.date :
    sDate = dtDate.strftime('%x')
else :
    sDate = dtDate.strfttime('%x %X')

Returns properly for date, but not datetime objects (returns 'datetime.datetime' object has no attribute 'strfttime')

Sorry for the brain dump, but I am completely out of ideas.

CodePudding user response:

If you look at the source code for the datetime class (or simply command click on datetime using an IDE on Mac), you'll notice that the datetime class actually is a subclass of date:

class datetime(date):
    ...

Therefore, isinstance(dtDate, date) will be true even if dtDate is a datetime object.

You can fix this by checking for the more specific type first:

if isinstance(dtDate, datetime):
    sDate = dtDate.strftime('%x %X')
elif isinstance(dtDate, date):
    sDate = dtDate.strftime('%x')

Full code:

from datetime import date, datetime

#  dtDate = date.today()
dtDate = datetime.now()

if isinstance(dtDate, datetime):
    sDate = dtDate.strftime('%x %X')
elif isinstance(dtDate, date):
    sDate = dtDate.strftime('%x')

print(sDate)
  • Related