logo

A Date With the Datetime Module in Python | Part - 1

Published on
 •  1 mins read
How to get current date with month, year and day using python

We can extract current date using two classes.

  1. Using date class
from datetime import date

today = date.today()
  1. Using datetime class
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

Subscribe to Newsletter