Skip to content Skip to sidebar Skip to footer

Extract Time From Datetime And Determine If Time (not Date) Falls Within Range?

The problem is that I want it to ignore the date and only factor in the time. Here is what I have: import time from time import mktime from datetime import datetime def getTimeCat

Solution 1:

This line:

str_time = datetime.strptime(Datetime, "%m/%j/%y %H:%M")

returns a datetime object as per the docs.

You can test this yourself by running the following command interactively in the interpreter:

>>> import datetime
>>> datetime.datetime.strptime('12/31/13 00:12', "%m/%j/%y %H:%M")
datetime.datetime(2013, 1, 31, 0, 12)
>>>

The time portion of the returned datetime can then be accessed using the .time() method.

>>> datetime.datetime.strptime('12/31/13 00:12', "%m/%j/%y %H:%M").time()
datetime.time(0, 12)
>>>

The datetime.time() result can then be used in your time comparisons.


Solution 2:

Use this only gives you time.

from datetime import datetime

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

Post a Comment for "Extract Time From Datetime And Determine If Time (not Date) Falls Within Range?"