0

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
Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
  • You can use `.date` and that should be enough? – Celius Stingher Dec 26 '19 at 23:28
  • 3
    Did you try `datetime.now().date()` or, perhaps, `datetime.now().strftime('%Y%m%d')` if you mean by `date` a string in the format `YYYYMMDD`? – accdias Dec 26 '19 at 23:28
  • I wasn't of `datetime.date`. If one of you would care to post an answer, I'll happily accept it. – Abhijit Sarkar Dec 26 '19 at 23:31
  • Everytime you are not sure what methods are available for an object, open an interactive Python session and type `dir(objectname)`. For `datetime`, for example, you can do `dir(datetime.datetime)`. – accdias Dec 26 '19 at 23:33

1 Answers1

2

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
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53