1

This is my code that I tried to use but it doesn't work since it's a string

from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M")
print("time=", current_time)
wake_up=0
x=current_time - wake_up - 0.40
wake_up = float(input("when are you gonna wake up"))
print(x)

I am trying to make a calculator where as it prints the current time. (for example 23:00) and then the input asks what time are you going to wake up and you write (for example 08:30) and the output should be "You will get 09:30 hours and minutes of sleep" or preferably "You will get 9 hours and 30 minutes of sleep"

I tried to do this but it is a string and cannot be calculated and I tried to find an integer version of the now.strftime module. Can someone help me find out how to do this?

qwerty
  • 51
  • 1
  • 5
  • Does this answer your question? [Converting date string to number for comparison](https://stackoverflow.com/questions/12097860/converting-date-string-to-number-for-comparison) – Grismar Dec 12 '19 at 03:41
  • @Grismar I think that's javascript – qwerty Dec 12 '19 at 03:46
  • Apologies, you are correct. This isn't though https://stackoverflow.com/questions/466345/converting-string-into-datetime (I didn't check that much because there's literally thousands of pages explaining this and the lack of any - possible troublesome - solution in the question indicates you likely didn't look very hard for an answer) – Grismar Dec 12 '19 at 23:28

2 Answers2

0

You'll need to use datetime.strptime(), which takes in a date string and a format string (reference here) and converts the string to a datetime object.

In your case, you would use the following to convert wake_up to a datetime object:

dt = datetime.strptime(wake_up, "%H:%M")
felipe
  • 7,324
  • 2
  • 28
  • 37
0

Modifications done based on your code:

from datetime import datetime, date
now_time = datetime.now().time()  # get time only
current_time_str = now.strftime("%H:%M")
print("time=", current_time_str)

#wake_up = input("when are you gonna wake up")
wake_up = '08:30'  # assuming this is user input
wake_up_time = datetime.strptime(wake_up, "%H:%M").time()
x = datetime.combine(date.today(), wake_up_time) - datetime.combine(date.today(), now_time)
print(str(x))  #also, you can get hours by x.seconds/3600

Other questions will help you.

Sangbok Lee
  • 2,132
  • 3
  • 15
  • 33