Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 971
T. Stone Avatar asked Sep 14 '09 20:09

T. Stone


People also ask

How do I check if a timestamp is null Python?

Using the is operator to check if a variable is NULL in Python. We can simply use the is operator or the = operator to check if a variable is None in Python. The following code uses the is operator to check if a variable is NULL in Python.

How do I print a datetime in Python without time?

You can use simply pd. to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD] . You can pass this as map/apply to use it in a dataframe/series too.

How do I fix AttributeError type object datetime datetime has no attribute datetime?

datetime' has no attribute 'datetime'. To resolve the problem, we just have to “import datetime” instead of “from datetime import datetime” as we did it above.


2 Answers

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
like image 88
hanksims Avatar answered Oct 04 '22 03:10

hanksims


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.

like image 30
spg Avatar answered Oct 04 '22 03:10

spg