How to fix 'NameError' in Python [duplicate] - python

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 3 years ago.
I have some code. When User write "Date" in input line, output must be date, like 2019-06-8 16:34:40
but program can not find input text - name 'date' is not defined
import datetime
x = input("Type your question here ... ")
########## Date ##########
now = datetime.datetime.now()
date = "Date"
if x == date:
print "Current date and time:"
print str(now)
########## (Can't find anything) ##########
else:
print("Something goes wrong ;( ")
Error -
NameError: name 'date' is not defined

In Python 3
import datetime
x = input("Type your question here ... ")
########## Date ##########
now = datetime.datetime.now()
date = "Date"
if x == date:
print ("Current date and time:")
print (str(now))
########## (Can't find anything) ##########
else:
print("Something goes wrong ;( ")
and the output is:
Type your question here ... Date
Current date and time:
2019-07-08 12:53:41.534617

Related

my dob code wont recognize days above 12 without triggering my input error text

my first code i have written whilst learning, and have become stuck on one issue.
NAME=str(input("Enter your name: "))
print ("hello",NAME)
from datetime import *
today = date.today()
print("Today: " + today.strftime('%A %d, %b %Y'))
good_value = False
value = ""
while good_value == False:
value = input("Insert Date in format dd/mm/yyyy: ")
try:
datetime.strptime(value, '%m/%d/%Y')
good_value = True
except ValueError:
print("Error: Date format invalid.")
thisYear = today.year
dob_data = value.split("/")
dobDay = int(dob_data[0])
dobMonth = int(dob_data[1])
ÁdobYear = int(dob_data[2])
dob = date(thisYear,dobMonth,dobDay)
if today == date(thisYear,dobMonth,dobDay):
print ("happy bithday", NAME)
else:
print ("its not your birthday, sucks to be you")
when i run the code it will work perfectly unless i type the date being over the 12th, so not breaking the error loop and obviously limiting the dates that can be put into the finished product.
Here
value = input("Insert Date in format dd/mm/yyyy: ")
you are informing user that format should be DD/MM/YYYY, but here
datetime.strptime(value, '%m/%d/%Y')
you are expecting MM/DD/YYYY. In order to repair this replace former using
value = input("Insert Date in format mm/dd/yyyy: ")
and
dobDay = int(dob_data[0])
dobMonth = int(dob_data[1])
using
dobDay = int(dob_data[1])
dobMonth = int(dob_data[0])
Observe that this did worked for values equal or less than 12 as there are 12 months

(Python) Getting errors when calculating range of dates

I've tried following examples such as https://www.pythonprogramming.in/get-range-of-dates-between-specified-start-and-end-date.html and Python generating a list of dates between two dates with various slightly different versions of the same code:
import datetime
from datetime import date, timedelta
def daterange():
while True:
d1 = input("Please enter in the earliest date: ")
check1 = d1.replace("-","")
if check1.isdigit:
d2 = input("Please enter in the latest date: ")
check2 = d2.replace("-","")
if check2.isdigit:
date1 = datetime.datetime.strptime(d1, '%d-%m-%Y').strftime('%Y,%m,%d')## this is to convert my intended input format
date2 = datetime.datetime.strptime(d2, '%d-%m-%Y').strftime('%Y,%m,%d')## this is to convert my intended input format
print (date1)
print (date2)
dd = [date1 + datetime.timedelta(days=x) for x in range (0,(date2-date1).days)]
print (dd)
return
else:
print("That was an invalid date")
else:
print("That was an invalid date")
And I'm getting the same error where it cannot do a subtraction in date2-date1:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Can anyone explain why and provide a solution?
You can't add a timedelta to a str, which is what you are doing. This line: date1 = datetime.datetime.strptime(d1, '%d-%m-%Y').strftime('%Y,%m,%d') creates a datetime obj, and then converts it back to str.
Change your code like so and it will work:
import datetime
from datetime import date, timedelta
def daterange():
while True:
d1 = input("Please enter in the earliest date: ")
check1 = d1.replace("-","")
if check1.isdigit:
d2 = input("Please enter in the latest date: ")
check2 = d2.replace("-","")
if check2.isdigit:
date1 = datetime.datetime.strptime(d1, '%d-%m-%Y')
date2 = datetime.datetime.strptime(d2, '%d-%m-%Y')
print (date1)
print (date2)
dd = [date1 + datetime.timedelta(days=x) for x in range (0,(date2-date1).days)]
print (dd)
return
else:
print("That was an invalid date")
else:
print("That was an invalid date")
if __name__ == '__main__':
daterange()

Fix for SyntaxError: 'return' outside function [duplicate]

This question already has answers here:
Why am I getting this error in python when i enter into next line of if-else condition?
(2 answers)
Closed 2 years ago.
I don't know how to solve this error but please help. I have written my code like this.
print("i am jarvis please tell me how can i help you...")
inp = input()
print (inp)
with inp as source:
print(recognising)
try:
query = webbrowser.open(inp)
results= (query)
print(results)
except Execetions as e:
print("write it again")
print (e)
return "none"
return query
A very straight forward code and I am getting frustrated with this error
C:\Users\good pc\Documents\Jarvis>"C:/Users/good pc/AppData/Local/Programs/Python/Python37-32/python.exe" "c:/Users/good
pc/Documents/Jarvis/jarvisdemo.py"
File "c:/Users/good pc/Documents/Jarvis/jarvisdemo.py", line 36
return "none"
^
SyntaxError: 'return' outside function
You are returning outside a function, wrap everything to a function and call it:
import wikipedia
import datetime
import cv2
hour = int(datetime.datetime.now().hour)
if hour >=0 and hour <=12:
print("good morning")
elif hour >12 and hour<16:
print("good afternoon")
elif hour >16 and hour<20:
print("good evening")
else :
print("good night")
print("i am jarvis please tell me how can i help you...")
def jar():
inp = input()
print (inp)
with inp as source:
print(recognising)
def jar():
inp = input()
print (inp)
with inp as source:
print(recognising)
try:
query = webbrowser.open(inp)
results = query
print(results)
except Execption as e:
print("write it again")
prin(e)
return "none"
return query
print(jar())

Error on datetime.datetime input

I have a menu, where I input a start and end-date. I get an error when I select choice 2 in below menu-item.
### Take action as per selected menu-option ###
if choice == 1: # Start with default window
print ("Starting Backtest from 2014-1-1 until 2015-12-31")
start = datetime.datetime(2014,1,1)
start = start.date()
end = datetime.datetime(2015,12,31)
end = end.date()
elif choice == 2:
## Get input ###
start = input('Enter Start date [Format: YYYY,M,D - 2014,1,23] : ')
start = datetime.datetime(start)
start = start.date()
end = input('Enter End date [Format: 2015,8,23] : ')
end = datetime.datetime(end)
end = end.date()
How is it possible that my menu-item 1 works but 2 doesn't?
The error is
TypeError: an integer is required (got type str)
Please help
Thanks
You might be getting that error because you are comparing a string to an integer. You can change between the two like so
>>> int('123')
>>> 123
>>> str(123)
>>> '123'
OK - after some scouring about, I found this question that helped me to the right answer.
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'
So I needed this code to get my script running smoothly. Under choice 2 you see the new code with strptime and strftime. Apparantly I need to go through strptime to get to strftime!
### Take action as per selected menu-option ###
if choice == 1: # Start with default window
print ("Starting Backtest from 2014-1-1 until 2015-12-31 (2 years)")
start = datetime.datetime(2014,1,1)
start = start.date()
end = datetime.datetime(2015,12,31)
end = end.date()
elif choice == 2:
## Get input ###
start_input = input('Enter Start date [Format: YYYY,M,D - 2014,01,23] : ')
start_dt_obj = datetime.datetime.strptime(start_input, '%Y,%m,%d')
start = datetime.datetime.strftime(start_dt_obj, '%Y,%m,%d')
end_input = input('Enter End date [Format: YYYY,M,D - 2015,08,23] : ')
end_dt_obj = datetime.datetime.strptime(end_input, '%Y,%m,%d')
end = datetime.datetime.strftime(end_dt_obj, '%Y,%m,%d')
However this makes my code run, but I would have like to keep the date as a date. The choice 2 code saves my date as a str unlike Choice 1. Hmm...

How to input a range of dates and turn it into a list? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I would like to be able to just input a range of dates rather than every single date as i'd like to do some time series work on this data. Here is my code so far:
import re
def date():
dates = []
user_input =''
pattern = re.compile('\d{2}.\d{2}.\d{2}')
while user_input != 'end':
user_input =raw_input("Please put folder with format yy.mm.dd or 'end': ")
if pattern.match(user_input):
dates.append(user_input)
elif user_input == 'end':
print 'Dates:'
else:
print "Use yy.mm.dd format or write 'end'"
return dates
I would suggest using datetime if you want to work with dates, as it is your regex will match any combination of dd.dd.dd:
from datetime import datetime
def date():
dates = []
user_input =''
while user_input != 'end':
user_input = raw_input("Please put folder with format yy.mm.dd or 'end': ")
try:
dte = datetime.strptime(user_input,"%y.%m.%d")
dates.append(dte)
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates
If you want a range of dates between start and end:
from datetime import datetime, timedelta
def date():
dates = []
while True:
start = raw_input("Please put start date with format yy.mm.dd or 'end': ")
if start == "end":
break
end = raw_input("Please put end date with format yy.mm.dd or 'end': ")
try:
start = datetime.strptime(start,"%y.%m.%d")
end = datetime.strptime(end,"%y.%m.%d")
for _ in xrange((end-start).days+1):
dates.append(start)
start += timedelta(days=1)
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates
pandas may also be useful:
from datetime import datetime
import pandas as pd
def date():
dates = []
while True:
start = raw_input("Please put start date with format yy.mm.dd or 'end': ")
if start == "end":
break
end = raw_input("Please put end date with format yy.mm.dd or 'end': ")
try:
start = datetime.strptime(start,"%y.%m.%d")
end = datetime.strptime(end,"%y.%m.%d")
dates.append(pd.date_range(start, end))
except ValueError:
print "Use yy.mm.dd format or write 'end'"
print 'Dates:'
return dates

Categories