Home > Enterprise >  How do I create an if-else based on datetime hour argument
How do I create an if-else based on datetime hour argument

Time:12-15

I need help writing a function depending on if a hour argument is passed to a datetime object or not.

Example with hour argument: start_date_dt = datetime(2020, 1, 1, 0) Example without: start_date_dt = datetime(2020, 1, 1)

Based on if the user passes one of the other I have an if else which generates. I tried the following as a test

if start_date_dt.minute is not None:
    print(start_date_dt)

else:
    print(False)

but I don't think it is right, because once the object is generated the 00:00:00 portion of the datetime is automatically created and is technically never not none.

Thank you in advance!

CodePudding user response:

I don't think it is possible out-of-the-box given that - if not passed - hour, minute and second are defaulted to 0:

d1 = datetime(2022, 12, 15)
d2 = datetime(2022, 12, 15, 0, 0, 0)

d1.hour == d2.hour     # True
d1.minute == d2.minute # True
d1.second == d2.second # True

You could write a wrapper class:

from datetime import datetime

class my_datetime:

    def __init__(self, year, month, day, hour = None, minute = None, second = None):
         hour, self.hour_passed = 0, False if hour is None else hour,True
         minute, self.minute_passed = 0, False if minute is None else minute,True
         second, self.second_passed = 0, False if second is None else second, True
         self.dt = datetime(year, month, day, hour, minute, second)

CodePudding user response:

If your upstream simply passes you the datetime object start_date_dt (with no other information), HH:MM:SS already resolved to 00:00:00, and I think it is almost impossible to determine if the upstream inputted hour=0 or left the hour argument "empty".

Logically it would require you to go one step backward that could make your upstream provide a bit more information to you, by means of a wrapper or a sub-class or whatever.

  • Related