This is my code to find the time difference. You input hour and time of your preference. Remaining time is calculated by finding the difference between your input and current time but it is not working for me.
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
print("Set Time: ", set_time)
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = set_time - current_time
print(dif)
I am able to get the set time and current time, but not the difference.
This is the output of the program:
Enter hour: 10
Enter minutes: 30
Set Time: 10:30
Current Time: 11:14
You are actually subtracting string from datetime, so convert the first input time to datetime first
time_hour = input("Enter hour: ")
time_minutes = input("Enter minutes: ")
set_time = time_hour + ":" + time_minutes
the_time = datetime.strptime(set_time,'%H:%M')
now = datetime.now()
current_time = now.strftime("%H:%M")
print("Current Time: ", current_time)
dif = the_time - current_time
print(dif)
Related
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = datetime.time(time1h,time1m,time1s)
time2 = datetime.time(time2h,time2m,time2s)
diff = datetime.timedelta(hours=(time2.hour - time1.hour), minutes=(time2.minute - time1.minute), seconds=(time2.second - time1.second))
print(diff)
I am trying to print the results from the diff variable separately from each other so I can format it like
"You ran for (diffhours) hours, (diffminutes) minutes, and (diffseconds) seconds"
Alternatively you could do something like this
output_string = str(diff).split(':')
print("You ran for {} hours, {} minutes, and {} seconds".format(*output_string))
While you can use diff.seconds and then carry out various calculations to convert it to hours and minutes as suggested in the other answers, it's also possible to convert diff to a string and process it that way:
diff = str(diff).split(':') # diff will be something like 1:01:23
print(f'You ran for {diff[0]} hours, {diff[1]} minutes and {diff[2]} seconds')
Example output:
You ran for 1 hours, 01 minutes and 01 seconds
Here is the code:
print("Enter your start time!")
time1h = int(input("Hour: "))
time1m = int(input("Minute: "))
time1s = int(input("Second: "))
print("Enter your finishing time!")
time2h = int(input("Hour: "))
time2m = int(input("Minute: "))
time2s = int(input("Second: "))
time1 = timedelta(hours=time1h, minutes=time1m, seconds=time1s)
time2 = timedelta(hours=time2h, minutes=time2m, seconds=time2s)
diff = time2-time1
total_sec = diff.total_seconds()
h = int(total_sec // 3600)
total_sec = total_sec % 3600
m = int(total_sec // 60)
s = int(total_sec % 60)
print(f"You ran for {h} hours, {m} minutes, and {s} seconds")
im fairly new with python but im tring to get a device to turn on for one minute and off for 3 minutes repeatedly from the times of 9am to 5pm and i can't get the if statement to reference the updated time from the loop any help would be greatly appreciated!!!
import datetime
import time
n = "on" #to be replaced with GPIO output
f = "off" #to be replaced with GPIO output
nt = "tis not be the time" #used to see if working or not
tt = "tis be time" #used to see if working or not
now = datetime.datetime.now()
hour = now.hour
def count():
now = datetime.datetime.now()
hour = now.second
total = 1
if hour >= 8 and hour <= 16:
now = datetime.datetime.now()
hour = now.hour
for i in range(1,100):
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.second
print (hour)
else :
for i in range(1,100):
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
count()
You could fix it with a while loop instead, it would look like this, just put all of it inside your function
now = datetime.datetime.now()
hour = now.hour
if hour >= 8 and hour <= 16:
run = True
else:
run = False
while run:
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.second
print (hour)
if hour >= 8 and hour <= 16:
run = True
else:
run = False
while run == False:
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
if hour >= 8 and hour <= 16:
run = True
else:
run = False
Maybe using a while statement. In addition, you have hour = now.second on the second line of the function count and I think it should be hour = now.hour.
See the code with comments:
import datetime
import time
n = "on" #to be replaced with GPIO output
f = "off" #to be replaced with GPIO output
nt = "tis not be the time" #used to see if working or not
tt = "tis be time" #used to see if working or not
#Next lines are redundant, commented out.
#now = datetime.datetime.now()
#hour = now.hour
def count():
now = datetime.datetime.now()
hour = now.hour #now.second
total = 1
while hour >= 8 and hour <= 16:
now = datetime.datetime.now()
hour = now.hour
# for i in range(1,100): -> why you need this?
total = total*2
print (tt)
print (n)
time.sleep(60)
print(f)
time.sleep(180)
now = datetime.datetime.now()
hour = now.hour #now.second
print (hour)
for i in range(1,100): #I don't know why you need a loop here
now = datetime.datetime.now()
hour = now.hour
print (nt)
print (hour)
time.sleep(10)
count()
Edited for correcting another hour = now.second inside the while loop
I don't know how are you planning on running the code, but the main problem I see is that you do not have any loop for your code to run infinitely and check the time condition.
Also it's not clear for me why you need this total variable that gets doubled.
Another thing is your for loops - the condition is not clear. Why do you want to run it in this specific range?
What I would do is I would create an infinite loop and inside it make some decisions based on a clear time conditions - the conditions that are specified by you.
So if I understood your case correctly I'd rather write something like this:
# between 9am to 5pm turn on the device for 60 seconds and off for 180 seconds repeatedly
from datetime import datetime
import time
def update_device_state(state):
# TODO: implement GPIO output code
pass
def run():
device_state = 'off'
new_state = device_state
on_timer = 0
off_timer = time.time() - 180 # initial value must be over 180 seconds to trigger device on a first run
while True:
hour = datetime.now().hour
if 5 <= hour <= 17:
if device_state == 'off' and time.time() - off_timer > 180:
on_timer = time.time()
new_state = 'on'
off_timer = 0
elif device_state == 'on' and time.time() - on_timer > 60:
off_timer = time.time()
new_state = 'off'
on_timer = 0
else:
if device_state = 'on'
new_state = 'off'
on_timer = 0
off_timer = time.time()
if device_state != new_state:
update_device_state(new_state)
device_state = new_state
time.sleep(1)
run()
But the code requires some testing as I just quickly drafted it and I just briefly red it.
I would like to get help with this program I have made. The function of the code is so the users can input a city anywhere in the world and they will then get data about the weather for that city.
I want it to restart the program from the top, but it only restarts the program from where the results are.
# - Weather Program -
#Import
import datetime
import requests
import sys
#Input
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
#Loop
while True:
#Program
if degrees < 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees < 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a mild " + "{:.1f}".format(degrees) +
"°C, you might need a jacket.")
elif degrees >= 20 and time > str(12.00):
print("\nGood afternoon " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
elif degrees >= 20 and time < str(12.00):
print("\nGood morning " + name_of_user + ".")
print("\nThe date today is: " +
day_of_month +
month +
year)
print("The current time is: " + time)
print("The humidity is: " + str(humidity) + '%')
print("Latitude and longitude for " + city + " is: " + str(latitude), str(longitude))
print("The temperature is a warm " + "{:.1f}".format(degrees) +
"°C, don't forget to drink water.")
#Loop
restart = input('Would you like to check another city (y/n)?: ')
if restart == 'y':
continue
else:
print('Goodbye')
sys.exit()
So this is what happens.. The loop only loops the question with the input and data already filled in.
What is your name?: Test
City Name: Oslo
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: y
Good afternoon Test.
The date today is: 01 May 2019
The current time is: 20:23:36
The humidity is: 76%
Latitude and longitude for Oslo is: 10.74 59.91
The temperature is a mild 12.7°C, you might need a jacket.
Would you like to check another city (y/n)?: n
Goodbye
Process finished with exit code 0
I want the code to loop from the top so I can press y so the program will ask me for another city to input.
You are never updating your values. Let's take a simpler example:
x = int(input("What is the number you choose? "))
while True:
if x >3:
print(x)
continue
else:
break
If I run this, I will get x printed out forever if I choose, say 5. The code defining x will never be re-run because it's outside of the loop. To fix this, I can move my code for x into the while loop:
while True:
x = int(input("What number do you choose? "))
if x>3:
print(x)
else:
break
This will run the code for x every time the loop executes, so x can now change. Applying this to your code:
# loop is now up near the top
while True:
# You want these values to change on each iteration of the while
# loop, so they must be contained within the loop
name_of_user = input("What is your name?: ")
city = input('City Name: ')
#API
api_address='http://api.openweathermap.org/data/2.5/weather?appid=<app_id_token>&q='
url = api_address + city
json_data = requests.get(url).json()
#Variables
format_add = json_data['main']['temp']
day_of_month = str(datetime.date.today().strftime("%d "))
month = datetime.date.today().strftime("%b ")
year = str(datetime.date.today().strftime("%Y "))
time = str(datetime.datetime.now().strftime("%H:%M:%S"))
degrees = format_add - 273.15
humidity = json_data['main']['humidity']
latitude = json_data['coord']['lon']
longitude = json_data['coord']['lat']
if degrees... # rest of your statements
Now the value for City can change, and you can apply that to the other data structures as well
Put your while loop starting above the first input. Don't forget to declare your constant variables above the main loop.
The while loop only covers the code that display the results, the code that takes input and request the results is only executed once.
You need to have everything except the import statements within the while loop
All you need to is put the input section and the API sections inside your while true loop.
I will say, I was unable to actually test my solution, but I am almost completely sure that it will work. Good luck!
Trying to make it so Largest Task is pointed out in the print. Got everything else just need to able to grab the Largest Task.
def main ():
print("*** TIME MANAGEMENT ASSISTANT ***") NumberOfTasks = int(input("Number of tasks: "))
total = 0.0
TotalHour = 0.0
Day = 0.0
Minute = 0.0
EndTimeMinute = 0.0
EndTimeHour = 0.0
EndTimeDay = 0.0
RemainingHour = 0.0
AverageMinutes = 0.0print("What time will you start (on a 24-hour clock)? ")
StartHour = int(input("Hour: "))
StartMinute = int(input("Minute: "))
for i in range (NumberOfTasks):
TaskName = input("Task description: ")
TaskTime = int(input("How many minutes will this task take? "))
total = int(total + TaskTime)
TotalHour = int(total//60)
Minute = int(total%60)
Day = int(TotalHour//24)
RemainingHour = int(TotalHour%24)
EndTimeDay = Day
EndTimeHour = TotalHour + StartHour
if EndTimeHour > 24:
EndTimeHour = int(total%60)
EndTimeMinute = Minute + StartMinute
AverageMinutes = float(total//NumberOfTasks)
print("TOTAL TIME:", Day, "day(s)", RemainingHour, "hour(s)", Minute, "minute(s)")
print("END TIME: ", "In ", EndTimeDay, " day(s) at ", EndTimeHour, ":", EndTimeMinute,sep="")
print("LONGEST TASK: ")
print("AVERAGE TASK LENGTH:", round(AverageMinutes,2), "minutes")
You need to record the time of each "task," and then calculate the longest after the loop by sorting. To implement this way, you need to ensure task names are unique, so I've added a line of code to do that (all additions are commented):
def main():
print("*** TIME MANAGEMENT ASSISTANT ***")
NumberOfTasks = int(input("Number of tasks: "))
total = 0.0
TotalHour = 0.0
Day = 0.0
Minute = 0.0
EndTimeMinute = 0.0
EndTimeHour = 0.0
EndTimeDay = 0.0
RemainingHour = 0.0
AverageMinutes = 0.0
print("What time will you start (on a 24-hour clock)? ")
StartHour = int(input("Hour: "))
StartMinute = int(input("Minute: "))
# create a dictionary to store time for each task
task_times = {}
for i in range (NumberOfTasks):
TaskName = input("Task description: ")
# ensure task name is unique
while TaskName in task_times.keys():
TaskName = input("Task description has already been used. Please enter a unique description: ")
TaskTime = int(input("How many minutes will this task take? "))
total = int(total + TaskTime)
TotalHour = int(total//60)
Minute = int(total%60)
Day = int(TotalHour//24)
RemainingHour = int(TotalHour%24)
EndTimeDay = Day
EndTimeHour = TotalHour + StartHour
if EndTimeHour > 24:
EndTimeHour = int(total%60)
EndTimeMinute = Minute + StartMinute
AverageMinutes = float(total//NumberOfTasks)
# record time for this task in the dictionary
task_times[TaskName] = TaskTime
print("TOTAL TIME:", Day, "day(s)", RemainingHour, "hour(s)", Minute, "minute(s)")
print("END TIME: ", "In ", EndTimeDay, " day(s) at ", EndTimeHour, ":", EndTimeMinute, sep="")
# calculate longest task by sorting by time and taking the last item
longest_task_name, longest_task_length = sorted(task_times.items(), key=lambda x: x[1])[-1]
print("LONGEST TASK: {}".format(longest_task_name))
print("AVERAGE TASK LENGTH:", round(AverageMinutes,2), "minutes")
How can I create a countdown clock in Python that looks like 00:00 (min & sec) which is on a line of its own. Every time it decreases by one actual second then the old timer should be replaced on its line with a new timer that is one second lower:
01:00 becomes 00:59 and it actually hits 00:00.
Here is a basic timer I started with but want to transform:
def countdown(t):
import time
print('This window will remain open for 3 more seconds...')
while t >= 0:
print(t, end='...')
time.sleep(1)
t -= 1
print('Goodbye! \n \n \n \n \n')
t=3
I also want to make sure that anything after Goodbye! (which would most likely be outside of the function) will be on its own line.
RESULT: 3...2...1...0...Goodbye!
I know this is similar to other countdown questions but I believe that it has its own twist.
Apart from formatting your time as minutes and seconds, you'll need to print a carriage return. Set end to \r:
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
time.sleep(1)
t -= 1
print('Goodbye!\n\n\n\n\n')
This ensures that the next print overwrites the last line printed:
Here is the code which counts from 01:05 to 00:00 in MM:SS format.
Python 3 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print(str(k)+str(i)+":"+str(j), end="\r")
else:
print(str(k)+str(i)+":"+str(k)+str(j), end="\r")
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print("Goodbye!", end="\r")
time.sleep(1)
countdown(1,5) #countdown(min,sec)
Python 2 :
import time
def countdown(p,q):
i=p
j=q
k=0
while True:
if(j==-1):
j=59
i -=1
if(j > 9):
print "\r"+str(k)+str(i)+":"+str(j),
else:
print "\r"+str(k)+str(i)+":"+str(k)+str(j),
time.sleep(1)
j -= 1
if(i==0 and j==-1):
break
if(i==0 and j==-1):
print "\rGoodbye!"
time.sleep(1)
countdown(1,5) #countdown(min,sec)
For the simplicity, this code is able to say you how long it takes until the next desired time, which might be whatever you want to do in your program. In your case, this is a kind of countdown timer.
from datetime import datetime
x=datetime.today()
y=x.replace(day=x.day+1, hour=3, minute=1, second=0, microsecond=0)
delta_t=y-x
secs=delta_t.seconds+1
second = (secs % 60)
minut = (secs / 60) % 60
hour = (secs / 3600)
print ("Seconds: %s " % (second))
print ("Minute: %s " % (minut))
print ("Hour: %s" % (hour))
print ("Time is %s:%s:%s" % (hour, minut, second))
Then, output is as follows:
Seconds: 50
Minute: 32
Hour: 12
Time is 12:32:50
Good luck with your coding.
Maybe this link will help:
Making a Timer in Python 3
And look at my answer, it is same for your too!
Anyway, here is answer:
import time
import os
hour = int(input('Enter any amount of hours you want -+==> '))
minute = int(input('Enter any amount of minutes you want -+==> '))
second = int(input('Enter any amount of seconds you want -+==> '))
time = hour*10800 + minute*3600 + second*60
print('{}:{}:{}'.format(hour,minute,second))
while time > 0:
time = time - 1
seconds = (time // 60) % 60
minutes = (time // 3600)
hours = (time // 10800)
print('Time Left -+==> ',hours,':',minutes,':',seconds,)
os.system("CLS")
if time == 0:
print('Time Is Over!')
Input:
Enter any amount of hours you want -+==> 0
Enter any amount of minutes you want -+==> 0
Enter any amount of seconds you want -+==> 10
Output # All are on the same line
Time Left -+==> 0:0:10
Time Left -+==> 0:0:9
Time Left -+==> 0:0:8
Time Left -+==> 0:0:7
Time Left -+==> 0:0:6
Time Left -+==> 0:0:5
Time Left -+==> 0:0:4
Time Left -+==> 0:0:3
Time Left -+==> 0:0:2
Time Left -+==> 0:0:1
Time Left -+==> 0:0:0
Time Is Over!
import time
import sys
print(' ')
print('Countdown Timer, By Adam Gay')
print(' ')
print('Instructions: Input time to countdown from.')
print(' ')
c=':'
hourz=input('Hours: ')
minz=input('Minutes: ')
secz=input('Seconds: ')
print(' ')
hour=int(hourz)
min=int(minz)
sec=int(secz)
while hour > -1:
while min > -1:
while sec > 0:
sec=sec-1
time.sleep(1)
sec1 = ('%02.f' % sec) # format
min1 = ('%02.f' % min)
hour1 = ('%02.f' % hour)
sys.stdout.write('\r' + str(hour1) + c + str(min1) + c + str(sec1))
min=min-1
sec=60
hour=hour-1
min=59
Print('Countdown Complete.')
time.sleep(30)