DEV Community 👩‍💻👨‍💻

Cover image for A Date With the Datetime Module in Python | Part - 1
Sahil
Sahil

Posted on • Originally published at sahilfruitwala.com

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

We can extract current date using two classes.

  1. Using date class
from datetime import date

today = date.today()
Enter fullscreen mode Exit fullscreen mode
  1. Using datetime class
from datetime import datetime

today = datetime.today()
Enter fullscreen mode Exit fullscreen mode

OR

from datetime import datetime

now = datetime.now()
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Today: 2022-10-22 17:13:37.918735
Year: 2022
Month: 10
Day: 22
Enter fullscreen mode Exit fullscreen mode

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
"""
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

Today: 2022-10-22 17:41:01.076569
Hour: 17
Minute: 41
Second: 1
Enter fullscreen mode Exit fullscreen mode

Want to learn more?
Signup for my Newsletter and get the best articles into your inbox.

Till the next time 👋

Top comments (0)

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout 😆