T. Stone
T. Stone

Reputation: 19495

Finding if a python datetime has no time information

I want to trap values that are like this (in which there is not 'time info' on the datetime):

datetime.datetime(2009, 4, 6, 0, 0)

Is there a better way to detect these values other than testing hour/minute/second?

if value.hour == 0 and value.minute == 0 and value.second == 0:
     # do stuff

Upvotes: 10

Views: 7841

Answers (6)

IvanJ
IvanJ

Reputation: 11

When you convert datetime to string you get the following results:

from datetime import datetime

str(datetime(2023, 4, 27, 17, 30, 0)) 
# 2023-04-27 17:30:00

str(datetime(2023, 4, 27, 17, 30, 0, 55))
# 2023-04-27 17:30:00.000055

str(datetime(2023, 4, 27, 0, 0, 0, 55))
# 2023-04-27 00:00:00.000055

str(datetime(2023, 4, 27))
# 2023-04-27 00:00:00

Therefore, you can evaluate like this:

if str(value).endswith("00:00:00"):
    # do stuff

Works for any version of python.

Upvotes: -2

Eugene Yarmash
Eugene Yarmash

Reputation: 150031

You could chain comparisons to make the code more concise:

if dt.hour == dt.minute == dt.second == 0:
    # do stuff

Alternatively, you can compare the time part of the datetime to time.min, i.e. '00:00:00':

from datetime import time

if dt.time() == time.min:
    # do stuff

Upvotes: 1

hanksims
hanksims

Reputation: 1539

In Python 3.4 and earlier

The time method works here. Evaluates as boolean false if there's zero'd-out time info.

if not value.time():
    # do stuff

Upvotes: 11

Mark
Mark

Reputation: 108567

I see nothing wrong with your method, but you could compare it to a 'zeroed' time object.

import datetime
dt = datetime.datetime(2009, 4, 6, 0, 0)
dt.time() == datetime.time()

Upvotes: 8

spg
spg

Reputation: 9847

For python 3.5 and above:

if value.hour == 0 and value.minute == 0 and value.second == 0 and value.microsecond == 0:
  # do stuff

For python lower than 3.5:

if not value.time():
  # do stuff

Explanation: the boolean evaluation of a datetime.time instance was changed in python 3.5 :

In boolean contexts, a time object is always considered to be true.

Changed in version 3.5: Before Python 3.5, a time object was considered to be false if it represented midnight in UTC. This behavior was considered obscure and error-prone and has been removed in Python 3.5. See bpo-13936 for full details.

Upvotes: 10

Ned Batchelder
Ned Batchelder

Reputation: 375814

Another option:

if not (value.hour or value.minute or value.second):
    # do stuff

Upvotes: -1

Related Questions