Following is the code to retrieve current date and time
import datetime
print(datetime.datetime.today())
Or
import datetime
print(datetime.datetime.now())
Code to display current hour of the day
from datetime import *
print(getattr(datetime.today(),'hour'))
Code to print current local date
In order to display the present local date we can use of today() method which is defined in the date class.
import datetime
date_object = datetime.date.today()
print(date_object)
Output:
2020-07-22
Function that can be used to see which attributes belong to the datetime module
dir(datetime)
Important classes of the datetime module
1. Date
2. Time
3. Datetime
4. Timedelta
Now what would be the output of the following code:
import datetime
date1 = datetime.date(2020, 7, 23)
print(date1)
Well the Answer is:
2020-07-23
The date() function is actually a constructor of the date class, and it take three arguments: Year, month, and date. This code can also be written as:
from datetime import date
date1 = date(2020, 7, 23)
print(date1)
Now try to write the code to display present date. It should be something like:
from datetime import date
date_today = date.today()
print("Today's date is", date_today)
Output:
Today's date is 2020-07-22
What if someone asks you to print today’s month, year and date separately?
You can print using the following code-
from datetime import date
date_today = date.today()
print("Today's day:", date_today.day, end= " ")
print("Today's month:", date_today.month, end= " ")
print("Today's year:", date_today.year)
Run this code and you should get the output as current month, year and date.
0 comments:
Post a Comment