Abhijit Sarkar
Abhijit Sarkar

Reputation: 24528

How to convert a datetime to a date?

I'm designing a class that takes a date argument defaulting to today. I understand datetime.now() gives the current timestamp, but am not able to find a way to convert the datetime instance to date. Obviously I can do date(datetime.now().year, datetime.now().month, datetime.now().day) but that's ugly, and in the off chance the code runs at the end of a day, month or year, will create an inconsistent instance of my class.

Python 3.x solutions only, please.

One option is using a static method.

@staticmethod
def _today():
    now: datetime = datetime.now()
    return date(now.year, now.month, now.day)

def __init__(self, start_date: date = _today(), bucket_size_hour: int = 1):
    pass

Upvotes: 0

Views: 79

Answers (1)

Celius Stingher
Celius Stingher

Reputation: 18367

You can try by adding .date at the end of the datetime object. Tweaking how you define datetime a litle bit like this should work for you:

datetime = datetime.today().date()

Output:

2019-12-26

Upvotes: 2

Related Questions