0
Time = datetime.datetime.now().time()

I wanted to find the difference in seconds between the Time above^ and the hour of the day: for example if the Time = 15:07:25.097519, so the hour of the day is 15:00:00, i want to store 445.097519‬ seconds to a variable. How can I do that? I am an amateur at this please help!!

ictwinner
  • 19
  • 5

2 Answers2

0
import datetime

now = datetime.datetime.now()
hour = now.replace(minute=0, second=0, microsecond=0)
seconds = (now - hour).seconds + (now - hour).microseconds / 1000000
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
0

Here is one way to do it. Extract the hour from current time, and initialize a new datetime.time object with hour as input. Then you convert both of the timestamps to datetime and then do the subtraction.
Code below does that

Time = datetime.datetime.now().time()
hour = str(Time).split(":")[0]
currentHourTime = datetime.datetime(2019,10,31,int(hour),0,0,0).time()

dateTimeCurr = datetime.datetime.combine(datetime.date.today(), Time)
dateTimeCurrHour = datetime.datetime.combine(datetime.date.today(), currentHourTime)

dateTimeDifference = dateTimeCurr - dateTimeCurrHour


dateTimeDifferenceInSeconds = dateTimeDifference.total_seconds()

print(dateTimeDifferenceInSeconds)
hsnsd
  • 1,728
  • 12
  • 30