Comparing the current time with a user input time WITHOUT the date
So I'm making a lighting routine and I need to do some time comparisons to see if I'm in the middle of a cycle or out of a cycle. Long story short, I'm having issues comparing a user input of time with the formatted time of the datetime module:
def userInput():
try:
a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M")
print (a.strftime("%H:%M"))
except:
print ("Please enter correct time in HHMM format")
return a
def timeComparator(a):
now = datetime.datetime.now().time()
#this obtains the current time
today = a
#if statement compares input from
print("the time now is: ", now)
if (now < today):
print ("hello human")
elif (now > today):
print ("hello plant")
if __name__=="__main__":
a = userInput()
timeComparator(a)
I'm getting the error "TypeError: '<' not supported between instances of 'datetime.time' and 'datetime.datetime'" which I guess means the formatting for comparing isn't compatible.
I DON'T need the date or anything else, just the current time. I'd like to just be able to compare if a user input time is before or after the current time.
Your today in the function timeComparator is a datetime object while your now is a time object. Just make sure your user_input returns a time object:
def userInput():
try:
a = datetime.datetime.strptime(input('When you would like to routine to start in HH:MM 24 hour format: '), "%H:%M").time() #<----- added .time()
print (a.strftime("%H:%M"))
except:
print ("Please enter correct time in HHMM format")
return a
Related
I am writing a program to track my working hours as a chef. I'm looking for it to ask when I started, finished and how long a break I had that day. The problem I am running into is I keep getting a value error on line 12 (time data '1900-01-01 10:00:00' does not match format '%H:%M') and I'm having trouble applying the threads on here that try to explain the solution to my own problem. I know what I need to do is extract some of the data from the datetime object as a whole but so far everything I have tried has thrown up an error.
Code below;
from datetime import datetime
fmt = "%H:%M" # The time format i.e hours and minutes
print("Please input your starting and finishing times for the following days.")
print("Wednesday:") # Denotes which day is being asked about
wed_start_in = (input("What time did you start?")) # asks starting time
wed_start = str(datetime.strptime(wed_start_in, "%H:%M")) # converts time start input into a datetime object
wed_finish_in = (input("And what time did you finish?")) # asks finishing time
wed_finish = str(datetime.strptime(wed_start_in, "%H:%M"))
wed_hours = datetime.strptime(wed_start, fmt) - datetime.strptime(wed_finish, fmt)
print(wed_hours)
You're converting back and forth into strings; instead, parse each of the times once, then keep them as times. Only convert them back to strings (if necessary) at the very end.
wed_start_in = input("What time did you start?") # asks starting time
wed_start = datetime.strptime(wed_start_in, "%H:%M") # converts time start input into a datetime object
wed_finish_in = input("And what time did you finish?") # asks finishing time
wed_finish = datetime.strptime(wed_finish_in, "%H:%M")
wed_hours = wed_finish - wed_start
print(wed_hours)
Trying to create an input validation for a date in format YYYY-MM-DD. I have two methods of doing this.
The first method seems to work, and loops back through to get input each time an error is raised.
The function in the second method is causing an infinite loop, but a nearly identical function in the first method does not.
If I enter a correctly formatted date in the second method, it prints as expected, but for any other input, it creates the infinite loop.
I'm not sure where this is breaking down?
I've looks in a number of Google results, and there are lots of date validations out there, but I haven't found one that explicitly addresses how to loop back around and try again.
I wasn't sure what else to try without essentially just rewriting method one.
import datetime as dt
#METHOD 1 - This is the first method for validating date input, which takes in individual blocks and validates each one individually.
def get_date(year_prompt, month_prompt, day_prompt):
#Year Input
while True:
try:
year = int(input(year_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if year in range(2000,3000,1):
break
else:
print("Sorry, your response must be in YYYY format and later than the year 2000.\n")
continue
#Month Input
while True:
try:
month = int(input(month_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if month in range(1,13,1):
break
else:
print("Sorry, needs to be MM and between 1-12\n")
continue
#Day Input
while True:
try:
day = int(input(day_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if day in range(1,32,1):
break
else:
print("Sorry, needs to be DD and between 1-31\n")
continue
#Takes the three inputs and puts them together into a date
date = dt.datetime(year, month, day)
#Returns the date
return date
#Runs the first method of getting and validating a date.
date = get_date("\nYYYY: ", "\nMM: ", "\nDD: ")
#Prints the validated date.
print("\nThe date you entered is: ", date, "\n")
#METHOD 2 - This is the second method for validating date, which takes in the whole date in one input, and attempts to validate it against the YYYY-MM-DD format.
def input_validation(date):
while True:
try:
dt.datetime.strptime(date, '%Y-%m-%d')
break
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
continue
return date
#Prints the validated date.
print("\nThe date you entered is: ", input_validation(input("Enter a date in format YYYY-MM-DD: ")), "\n")
My expected result for the second method, is either a date in format YYYY-MM-DD, or an error message that then asks for the input again.
You can get rid of the infinite loop while True, and return True or False based on the date being in the correct format
def input_validation(date):
#Flag to check date format
flag = False
try:
#If date is of correct format, set flag to True
dt.datetime.strptime(date, '%Y-%m-%d')
flag = True
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
#Return flag
return flag
print(input_validation('2019-01-31'))
print(input_validation('2019-001-31'))
print(input_validation('2019-01-311'))
The output will be
True
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
You can wrap this function around your while True to continue taking input from user
while True:
date_str = input('Enter Date')
if input_validation(date_str):
break
I'm trying to make a basic program that shows how many days are left until your next birthday, however when I run it in terminal, it says that the input value should be returning a string not an integer? when using the input function in python, doesnt it automatically return as a string value?
import datetime
currentDate = datetime.date.today()
userinput = input("Please enter your birthday(MM.DD.YY)")
birthday = datetime.datetime.strptime(userinput, "%m/%d/%Y")
print(birthday)
Use %y (small letter) to catch two digit years
You should advice the user about the expected format - you expect "MM/DD/YY", but you tell the user to type "MM.DD.YY"
To calculate the difference use something like this (for python3, for python2 use raw_input as Jahangir mentioned):
import datetime
today = datetime.date.today()
userinput = input("Please enter your birthday(MM/DD):")
birthday = datetime.datetime.strptime(userinput, "%m/%d")
birthday = datetime.date(year=today.year, month=birthday.month, day=birthday.day)
if (birthday-today).days<0:
birthday = datetime.date(year=today.year+1, month=birthday.month, day=birthday.day)
print("%d days to your next birthday!"%(birthday-today).days)
In Python 2 use raw_input() instead.
I would appreciate it if you could help me create a few lines of code that change the answer into a number of seconds stored as an integer in a variable.
import datetime
def get_dt():
a_raw = raw_input('Enter time a. Format: HH:MM:SS ')
b_raw = raw_input('Enter time b. ')
try:
a = datetime.datetime.strptime(a_raw, '%H:%M:%S')
b = datetime.datetime.strptime(b_raw, '%H:%M:%S')
print (b - a)
except ValueError:
print "Invalid format!"
get_dt()
get_dt()
Not having a Python 3 installation on my machine I converted your code to Python 3 with the following changes:
raw_input became input
print became print()
Additionally I fixed passing the values from one function to the other.
In order to get the time difference in seconds you can apply .total_seconds() to a datetime.timedelta such as b-a is:
#!/usr/bin/env python3
# coding: utf-8
import datetime
def get_dt():
a = input('Enter time a. Format: HH:MM:SS ')
b = input('Enter time b. ')
return a, b
def calc_seconds():
a, b = get_dt()
try:
a = datetime.datetime.strptime(a, '%H:%M:%S')
b = datetime.datetime.strptime(b, '%H:%M:%S')
delta_secs = (b-a).total_seconds()
print(delta_secs)
except ValueError:
print("Invalid format!")
calc_seconds()
calc_seconds()
In actual fact, I managed to do it by just adding
.totalseconds()
after
time = b-a
This is probably very simple, but I am a beginner in python and I wanted to compare birthday dates by prompting a user to enter a date in MM-DD format. No year because year is current year (2011). It will then prompt the user to enter another date, and then the program compares it to see which one is first. Then it prints out the earlier day and it's weekday name.
Example: 02-10 is earlier than 03-11.
02-10 is on thursday and 03-11 is on friday
I just started learned modules and I know i'm supposed to use the datetime module, a date class and strftime to get the weekday name. I don't really know how to put it all together.
If someone can help me get started that would really help! I have some bits and pieces together:
import datetime
def getDate():
while true:
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
userInput = datetime.date.strftime(birthday1, "%m-%d")
except:
print "Please enter a date"
return userInput
birthday2 = raw_input("Please enter another date (MM-DD): ")
if birthday1 > birthday2:
print "birthday1 is older"
elif birthday1 < birthday2:
print "birthday2 is older"
else:
print "same age"
There are a few problems I can see in the code you've posted. I hope it will be helpful to point some of these out, and provide a somewhat rewritten version:
Indentation is broken, but I guess this might just be problems pasting it into Stack Overflow
strftime is for formatting times, not parsing them. You want strptime instead.
In Python, True has a capital T.
You're defining the getDate function but never using it.
You would never exit your while loop, since you don't break after getting the input successfully.
It's considered bad style to use "camel case" for variable and method names in Python.
You use the word "older" in reference to the dates, but without a year you can't say if one person is older than the other.
You catch any exception thrown when you try to parse the date, but don't display it or check its type. That's a bad idea since if you've mistyped a variable name (or some similar typo) on that line, you won't see the error.
Here's a rewritten version of your code that fixes those problems - I hope it's clear from the above why I made those changes:
import datetime
def get_date(prompt):
while True:
user_input = raw_input(prompt)
try:
user_date = datetime.datetime.strptime(user_input, "%m-%d")
break
except Exception as e:
print "There was an error:", e
print "Please enter a date"
return user_date.date()
birthday = get_date("Please enter your birthday (MM-DD): ")
another_date = get_date("Please enter another date (MM-DD): ")
if birthday > another_date:
print "The birthday is after the other date"
elif birthday < another_date:
print "The birthday is before the other date"
else:
print "Both dates are the same"
There are two main functions that are used for converting between a date object and a string: strftime and strptime.
strftime is used for formatting. It returns a string object.
strptime is used for parsing. It returns a datetime object.
More info in the docs.
Since what you want is a datetime object, you would want to use strptime. You can use it as follows:
>>> datetime.datetime.strptime('01-23', '%m-%d')
datetime.datetime(1900, 1, 23, 0, 0)
Note that not having the year being parsed will set the default to 1900.
Well, datetime.date.strftime requires datetime object instead of string.
In your case the best thing is to create date manually:
import datetime
...
birthday1 = raw_input("Please enter your birthday (MM-DD): ")
try:
month, day = birthday1.split('-')
date1 = datetime.date(2011, int(month), int(day))
except ValueError as e:
# except clause
# the same with date2
And then when you have two dates, date1 and date2, you can just do:
if d1 < d2:
# do things to d1, it's earlier
else:
# do things to d2, it'2 not later