We can extract current date using two classes.
- Using
dateclass
from datetime import date
today = date.today()
- Using
datetimeclass
from datetime import datetime
today = datetime.today()
OR
from datetime import datetime
now = datetime.now()
The main difference between date.today() and datetime.today() is that date class just return the date object. Whereas, datetime class returns not only date but time as well.
Extract Current Day, Month and Year using Python
today = datetime.today()
print(f"Today: {today}")
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
OUTPUT:
Today: 2022-10-22 17:13:37.918735
Year: 2022
Month: 10
Day: 22
Extract Day of the Week using Python
today = datetime.today()
print(f"Today: {today}")
print(f"Weekday: {today.weekday()}")
"""
OUTPUT:
Today: 2022-10-22 17:32:48.396792
Weekday: 5
"""
This weekday() method will work with both the date and datetime class.
Note: Here, weekday() method will return index between 0 to 6.
Extract Current Time using Python
today = datetime.now()
print(f"Today: {today}")
print(f"Hour: {today.hour}")
print(f"Minute: {today.minute}")
print(f"Second: {today.second}")
OUTPUT:
Today: 2022-10-22 17:41:01.076569
Hour: 17
Minute: 41
Second: 1
Want to learn more?
Signup for my Newsletter and get the best articles into your inbox.
Till the next time 👋
Top comments (0)