Petr Laškevič
asked on
Why doesn't datetime module work as it should?
Hello, I wanted to make a simple program that could count how old a person using it is, according to his/her birthday and datetime module. import datetime
How to write this code correctly?
now = datetime.now()
if day == now.day and month == now.month:
age = now.year - year
if day != now.day or month != now.month:
age = now.year - age - 1
if now.year - year == -1:
print("Be serious, please.")
if now.year - rok < -1:
print("Be serious,please.")
print(věk)
I did this according to tutorials I found on the Internet, but when I want to run this piece of code, it says this: AttributeError: module 'datetime' has no attribute 'now' This project's purpose is only to show approximate age of people,so just the basics.How to write this code correctly?
ASKER
When I run this code:
And when I replace now.day with a variable I assigned to now.day,it also gives me this error.
from datetime import datetime
now = datetime.now()
if day == now.day and month == now.month:
age = now.year - year
if day != now.day or month != now.month:
age = now.year - age - 1
if now.year - year == -1:
print("Be serious, please.")
if now.year - rok < -1:
print("Be serious,please.")
print(age)
It gives me the following error: TypeError: unsupported operand type(s) for -: 'int' and 'str'And when I replace now.day with a variable I assigned to now.day,it also gives me this error.
now = datetime.now()
today = now.day
current_month = now.month
current_year = now.year
if day == now.day and month == now.month:
age = current_year - year
if day != now.day or month != now.month:
age = current_year - age - 1
if current_year - year == -1:
print("Be serious, please.")
if now.year - rok < -1:
print("Be serious,please.")
print(age)
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much. I forgot to close this question, so I close it two month later.
You don't show the import statement, but I guess, that this is a common issue with two solutions
solution one:
Open in new window
solution two:
Open in new window
the problem is, that the module datetime, contains an object with the same name as the module.
I personally am not really a big fan of this 'concept' and would at least advise against this whenever you create your own modules.
For existing modules you just have to pay attention to use the right import statement (from datetime import datetime) or you use double prefixes everywhere (datetime.datetime)