Search code examples
pythonpython-datetime

How to remove date from datetime object


I have a method that converts a string to a datetime object using strptime("%I:%M %p"), I only want the hours in 24 and minutes without any dates, because I will get the difference between this time and another time. The problem is that when I try to get the difference with total_seconds(), it gets difference in negative because the date in the strptime is "1900-01-01". Does any one have any ideas how to solve this?

My Code:

fTime = datetime.strptime(time, "%I:%M %p")
if 0 < (fTime - datetime.now()).total_seconds() <= 3600:
   return True

Solution

  • You can take one of two approaches: strip the date out of now, or add the current date to fTime. The first approach makes little sense, since you can't compare time objects like that anyway.

    To convert fTime to a proper datetime, datetime.combine it with date.today():

    fDate = datetime.combine(date.today(), fTime.time())
    return 0 < (fDate - datetime.now()).total_seconds() <= 3600
    

    Alternatively, you can replace the date portion:

    today = date.today()
    fDate = fTime.replace(year=today.year, month=today.month, day=today.day)
    

    Personally, I would go with combine because it's less awkward code.