Sir Muffington
Sir Muffington

Reputation: 321

How to compare DateTime object with an integer?

How do I compare an object datetime.datetime.now().time() with an integer like 12?

I need to make an if condition, which checks whether the time of day is before 12PM or after 12PM and take corresponding action.

Upvotes: 3

Views: 5793

Answers (6)

martineau
martineau

Reputation: 123473

You can't compare a datetime instance with an integer directly, but you can convert one to an integer by first using the timestamp() method to convert it to a floating-point value, and then converting that to an integer with the built-in round() function.

In the code below, an integer representing noon on the current day is created, and then that's compared to an integer representing the current date and time.

Since this requires one or more intermediate steps, it would probably be more efficient to just create a datatime object representing 12 pm on the current day and compare that to current date and time (as you do in your own answer).

import datetime

now = datetime.datetime.now()
noon = datetime.datetime(now.year, now.month, now.day, hour=12)

noon_today = round(noon.timestamp())  # Convert to integer.
now_as_int = round(now.timestamp())

if now_as_int < noon_today:
     print("before noon")
else:
     print("noon or later")

Upvotes: 1

Sir Muffington
Sir Muffington

Reputation: 321

Simple: you don't. You create a datetime object to compare instead:

import datetime
a = datetime.datetime.now().time()
b = datetime.time(12, 00, 00, 000000)
if a < b:
     print("Do x here")
else:
      print("Do y here")

Upvotes: 3

Anshul Choudhary
Anshul Choudhary

Reputation: 305

Apart from above mentioned solutions, you could also do this:

import time
d = time.localtime()
if d.tm_hour > 12 && d.tm_sec>0:
   ...

There is a thread that discuss why using time module could be better than datetime.

Upvotes: 1

hygull
hygull

Reputation: 8740

This can be easily checked using .strftime("%p"). Just have a look into below example.

Based on your area time may differ but still you can test it for different timezones. Check pytz for that.

If you get

  1. PM, that means, it's after 12 PM inclusive (and before midnight)
  2. AM, that means, it's before 12 PM (and from midnight onwards)

Example code:

import datetime

now = datetime.datetime.now() 
print(now) # 2019-10-04 22:11:46.655252
print(now.strftime("%p")) # PM
print(now.time().strftime("%p")) # PM

Upvotes: 1

Daniel Ocando
Daniel Ocando

Reputation: 3764

The class datetime.time() has an hour attribute that you can use for your purpose.

import datetime

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

if datetime_object.hour >= 12:
    print("Wow it's after 12 pm")
else:
    print("Wow it's before 12 pm")

Upvotes: 1

JulienV
JulienV

Reputation: 368

d = datetime.datetime.now().time()
if d.hour > 12:
...

Upvotes: 3

Related Questions