python - datetime output time only - python

The function below takes in HH:MM:SS but returns the date. I just want to enter the time and get out the time.
desired:
enter 23:23:23 > returns 23:23:23
currently:
enter 23:23:23 > returns 1900-01-01 23:23:23
question:
How do i get it to return only 23:23:23 time.
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()
Completed Code:
import datetime
def ObtainTime():
while True: #Infinite loop
userInDate = raw_input("Type Time HH:MM:SS ")
try:
d = datetime.datetime.strptime(userInDate, "%H:%M:%S")
d = d.time()
break #this will stop the loop
except ValueError:
print "Invalid Input. Please try again.\n"
return d
print ObtainTime()

Use datetime.time() to get the time.
Example -
>>> d = datetime.datetime.strptime("23:23:23","%H:%M:%S")
>>> d.time()
datetime.time(23, 23, 23)

Related

Can't figure out why I cannot invalidate an input if it is not YYYY-MM-DD in python

What I'm trying to do is get an input in the YYYY-MM-DD specific format and it will output the amount of minutes someone has lived since their birthdate. But the function "invalidate" only seems to create errors. Without it the code works as long as you input the correct format. I've tried some regex code but haven't been able to make it work either. Also, would it be easier to do this within a class?
import datetime
import inflect
import sys
import re
##class Date:
##def __init__(self, year, month, day):
def main():
birth = input("Birthdate: ")
##birthdate = invalidate(birth)
print(num_to_words(days_between(format_date(birth))) + " minutes")
##def invalidate(x):
#if x != "%Y-%m-d":
#sys.exit("Invalid")
def format_date(e):
year, month, day = map(int, e.split('-'))
date1 = datetime.date(year, month, day)
return date1
def days_between(f):
today = datetime.date.today()
diff = today - f
x = diff.days * 24 * 60
return x
def num_to_words(x):
p = inflect.engine()
words = p.number_to_words(x)
return words
if __name__ == "__main__":
main()
You need to check it with strptime to see if it actually matches the format, not the exact string:
import datetime
def invalidate(x):
# You were missing the % on d
try:
datetime.datetime.strptime(x, r'%Y-%m-%d')
except ValueError:
return False # Or change this to exit
return True # You could return your datetime object here too
>>> invalidate('2022-06-05')
True
>>> invalidate('2022-6-05')
True
>>> invalidate('')
False
>>> invalidate('2022')
False
In your original function, you were checking the exact match of the string:
>>> invalidate('%Y-%m-d') # This was the only thing that would match
>>> invalidate('2022-6-5')
Invalid
Modify your invalidate function to this:
def invalidate(x):
if re.match(r'^\d{4}-\d{2}-\d{2}$', x):
if datetime.datetime.strptime(x, '%Y-%m-%d'):
return datetime.datetime.strptime(x, '%Y-%m-%d')
else:
print("Invalid date")
sys.exit()
else:
print("Invalid date")
sys.exit()
I have modified my code which now has an additional valid date check after valid format check.

How to check if a datetime is in %d/%m/%Y AND if its greater than a certain datetime

I'm trying to make it so that it checks if its in the format I want and if its greater than today's date. I want it to ask for input until it gets a right answer but I can't find a way to do so.
while True:
try:
x=dt.datetime.strptime(input(), '%d/%m/%Y')
break
except ValueError:
print(1)
You can use the today class method to get a datetime object representing today's date, and use the > or < operator to compare it to the parsed x:
while True:
try:
x = dt.datetime.strptime(input(), '%d/%m/%Y')
if x > dt.datetime.today():
break
else:
print('before today')
except ValueError:
print('wrong format')
from datetime import datetime, date
while True:
input_ = input('Enter a date -> ')
try:
dt = datetime.strptime(input_, '%d/%m/%Y').date()
except ValueError:
dt = None
today = date.today()
if dt and dt > today:
break
print('All good!')
->
Enter a date -> 12/01/2021
Enter a date -> 18/01/2021
Enter a date -> 25/01/2021
Enter a date -> 14/02/2021
All good!
Customized your existing code to handle - a) Valid Date Check b) Greater than Today's Date condition.
import datetime as dt
while True:
try:
x = dt.datetime.strptime(input(), '%d/%m/%Y')
if x > dt.datetime.now():
print(x)
break
else:
print("Please Enter a Valid Date:")
except ValueError:
print("Invalid Date Format")
My solution;
import datetime as dt
todays_date = dt.datetime.now()
todays_seconds = todays_date.timestamp()
done = False
while not done:
user_input = input(f"Please type a date later that today's date ({todays_date.strftime('%d/%m/%Y')}): ")
try:
x = dt.datetime.strptime(user_input, '%d/%m/%Y')
if x.timestamp() <= todays_seconds:
print("Date must be after today's date")
else:
done = True
except ValueError:
print('Input not understood, please try again')
Gives;
Please type a date later that today's date (30/01/2021): 30/01/2021
Date must be after today's date
Please type a date later that today's date (30/01/2021): 31/01/2021
Process finished with exit code 0

How would I limit the user input() to only entering data once per day? I was thinking maybe the datetime stamp but unsure how to implement this

here is my code for retrieving the user input:
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
and my code for recording the input into a list:
ansQ1 = []
ansQ1.append(inputQ1())
print(ansQ1)
how do I now ask for this user input again, just once per day?
You can use datetime.datetime.now():
from datetime import datetime
def inputQ1():
while True:
try:
Q1A = int(input("Rate your exercise today on scale 1-100: "))
except ValueError:
print("invalid value")
continue
else:
return Q1A
dates = []
ansQ1 = []
while True:
today = datetime.now().strftime("%Y-%m-%d")
if today not in dates:
ansQ1.append(inputQ1())
dates.append(today)
print(ansQ1)
Where datetime.now().strftime("%Y-%m-%d") returns the current date in the from of 2020-05-21.
One thing to note, it isn't a very good practice to rely on try - except to convert an input into an int. Instead, use the str.isdigit() method:
def inputQ1():
while True:
Q1A = input("Rate your exercise today on scale 1-100: ")
if Q1A.isdigit():
return int(Q1A)
print("invalid value")

How To Have User Input Date and Subtract from It

What I want is a user input a selected date, and subtract that date from the current date, and then create a sleep timer according to the results.
from datetime import tzinfo, timedelta, datetime
def ObtainDate():
isValid=False
while not isValid:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
d1 = datetime.datetime.strptime(userIn, "%m/%d/%y")
isValid=True
except:
print "Invalid Format!\n"
return d1
t = (datetime.now() - d1).seconds
My current current code looks like this, but I cannot figure out how to get d1 and subtract the current date from it.
Since you are importing the class using
from datetime import tzinfo, timedelta, datetime
you are no longer importing the whole datetime module under that name, but individual classes directly into your script's namespace. Therefore your input parsing statement should look like this:
d1 = datetime.strptime(userIn, "%m/%d/%y") # You are no longer
The following will give you the difference in seconds between now and the entered time:
t = (datetime.now() - d1).total_seconds()
And as for the second part, there are many ways to implement a timer. One simple way is
import time
time.sleep(t)
EDIT
Here is the whole thing together:
from datetime import tzinfo, timedelta, datetime
def ObtainDate():
isValid=False
while not isValid:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
d1 = datetime.strptime(userIn, "%m/%d/%y")
isValid=True
except:
print "Invalid Format!\n"
return d1
t = (ObtainDate() - datetime.now()).total_seconds()
print t
Your code has a few simple errors. This version works (though I'm not sure exactly what you need, it should get you past your immediate problem).
from datetime import datetime
def ObtainDate():
while True:
userIn = raw_input("Type Date: mm/dd/yy: ")
try:
return datetime.strptime(userIn, "%m/%d/%y")
except ValueError:
print "Invalid Format!\n"
t0 = datetime.now()
t1 = ObtainDate()
td = (t1 - t0)
print t0
print t1
print td
print td.total_seconds()
Your main problem was that you were not calling your function. I have also simplified your while loop to an infinite loop. The return statement will break out of the loop unless it raises an error.

How can I validate a date in Python 3.x?

I would like to have the user input a date, something like:
date = input('Date (m/dd/yyyy): ')
and then make sure that the input is a valid date. I don't really care that much about the date format.
Thanks for any input.
You can use the time module's strptime() function:
import time
date = input('Date (mm/dd/yyyy): ')
try:
valid_date = time.strptime(date, '%m/%d/%Y')
except ValueError:
print('Invalid date!')
Note that in Python 2.x you'll need to use raw_input instead of input.
def validDate(y, m, d):
Result = True
try:
d = datetime.date(int(y), int(m), int(d))
except ValueError, e:
Result = False
return Result
and in the program use the function defined previously:
if not validDate(year_file, month_file, day_file):
return 0
Max S.,
Thanks for the code. Here is how I implemented it:
while True:
date = input('Date (m/dd/yyyy): ')
try:
date = time.strptime(date, '%m/%d/%Y')
break
except ValueError:
print('Invalid date!')
continue

Categories