Home > Mobile >  How to subtract time in python?
How to subtract time in python?

Time:11-17

I'm using python==3.10 And I'm trying to subtract two time values from each other. Now I have tried bunch of ways to do that but getting errors.

day_time = timezone.now()
day_name = day_time.strftime("%Y-%m-%d %H:%M:%S")
end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %H:%M:%S')
print(end_Time- day_name)

error : TypeError: unsupported operand type(s) for -: 'str' and 'str'

also tried.

    day_time = timezone.now()
    end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %H:%M:%S')
    print(end_Time- day_time)

error : TypeError: can't subtract offset-naive and offset-aware datetimes

and This as well.

        day_time = timezone.now()
        end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %H:%M:%S.000000.00 00')
        print(end_Time- day_time)

error: ValueError: time data '2022-11-27 00:00:00' does not match format '%Y-%m-%d %H:%M:%S.000000.00 00'

CodePudding user response:

Your second approach is almost right, but you should use

day_time = datetime.now()

When you subtract you will get a a datetime.timedelta object

I think the issue with your second approach is that by using timezone you also have the timezone as part of the datetime, instead of just the date and time.

CodePudding user response:

I have solved this problem by doing the following approach.

        #first i get the current time
        day_time = timezone.now()
        #second converted that into end_time format
        day_time = day_time.strftime("%Y-%m-%d %H:%M:%S")
        #third converted that string again into time object
        day_time = datetime.strptime(day_time, '%Y-%m-%d %H:%M:%S')
        end_Time = datetime.strptime(latest_slots.end_hour, '%Y-%m-%d %H:%M:%S')

CodePudding user response:

You can solve this by using a combination of the datetime and timedelta libraries like this:

from datetime import datetime,timedelta
day_time = datetime.now()
end_time = datetime.now()   timedelta(days= 2,hours =7)
result = end_time - day_time
print(result)

# Output :--> 2 days, 7:00:00.000005
  • Related