Home > Blockchain >  Python check whether `datetime` is the beginning of the day?
Python check whether `datetime` is the beginning of the day?

Time:08-06

For type datetime.datetime, how do we check whether the timestamp points to the beginning of the day?

The beginning of the day means the time 00:00:00.000000 of the day, while the date part can be anyone.

CodePudding user response:

Use datetime.time.min to get the earliest possible time (the beginning of the day) and compare it to your_datetime.time()

your_datetime.time() == datetime.time.min

CodePudding user response:

Something like this will take care of it. In this example I am comparing with the current time. datetime.time() with no arguments is initialised to (0,0).

datetime.time() == datetime.datetime.now().time()

CodePudding user response:

One way is to format the datetime using "%H:%M:%S.%f" and check if the value is "00:00:00.000000".

from datetime import datetime

d1 = '2022-10-27T05:23:20.000000'
d2 = '2022-10-27T00:00:00.000000'

fmt = "%Y-%m-%dT%H:%M:%S.%f"
dt1 = datetime.strptime(d1, fmt)
dt2 = datetime.strptime(d2, fmt)

print(dt1, dt1.strftime("%H:%M:%S.%f") == "00:00:00.000000")
print(dt2, dt2.strftime("%H:%M:%S.%f") == "00:00:00.000000")

Output:

2022-10-27 05:23:20 False
2022-10-27 00:00:00 True

Another way is check if the time fields in a datetime object are all 0.

if dt2.hour == dt2.minute == dt2.second == dt2.microsecond == 0:
    print("dt at beginning of the day")
  • Related