C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Caution: This program is correct. But if you remove the "from import" statement, it will result in NameErrors.
Python program that uses import star syntax
from datetime import *
def yesterday():
today = date.today()
yesterday = today - timedelta(days=1)
return yesterday
print(date.today())
print(yesterday())
Output
2014-04-17
2014-04-16
Tip: We can specify multiple modules from one package using a comma between each name. This reduces the line count of the program.
Alternate syntax 1: Python
from datetime import date, timedelta
Alternate syntax 2: Python
from datetime import date
from datetime import timedelta
However: The program fails at the line where we assign "yesterday." The print statement is never reached.
PrintPython program that causes NameError
from datetime import date
today = date.today()
yesterday = today - timedelta(days=1)
print(yesterday)
Output
Traceback (most recent call last):
File "C:\programs\file.py", line 8, in <module>
yesterday = today - timedelta(days=1)
NameError: name 'timedelta' is not defined
Tip: The module file must be in the same directory as your program. And its name must equal the name in your "import" statement.
Example file, stock.py: Python
def buy():
print("stock.buy called")
Python program that uses stock module, file.py
import stock
# Call the method in the stock module.
stock.buy()
Output
stock.buy called