Python Dates and Time

Python provides the datetime module to work with dates and times. It allows you to get the current date and time, format dates, and perform date calculations. Get Current Date and Time Example Output: Output will vary based on the current date and time. Get Current Date Example Output: Get Current Time Example Output: Create […]

2 mins read Lesson 11 of 56 20% through track

Python provides the datetime module to work with dates and times. It allows you to get the current date and time, format dates, and perform date calculations.

Get Current Date and Time

Example

import datetime

current = datetime.datetime.now()

print(current)

Output:

2026-05-31 14:30:45.123456

Output will vary based on the current date and time.

Get Current Date

Example

import datetime

today = datetime.date.today()

print(today)

Output:

2026-05-31

Get Current Time

Example

import datetime

current_time = datetime.datetime.now().time()

print(current_time)

Output:

14:30:45.123456

Create a Specific Date

Example

import datetime

date = datetime.datetime(2026, 5, 31)

print(date)

Output:

2026-05-31 00:00:00

Display Year, Month, and Day

Example

import datetime

today = datetime.datetime.now()

print(today.year)
print(today.month)
print(today.day)

Output:

2026
5
31

Format Date Using strftime()

The strftime() method formats date and time into a readable string.

Example

import datetime

today = datetime.datetime.now()

print(today.strftime("%d-%m-%Y"))

Output:

31-05-2026

Common Format Codes

CodeDescriptionExample
%dDay31
%mMonth05
%YYear2026
%HHour (24-hour)14
%MMinute30
%SSecond45
%AWeekday NameSunday
%BMonth NameMay

Get Weekday Name

Example

import datetime

today = datetime.datetime.now()

print(today.strftime("%A"))

Output:

Sunday

Date Difference

Example

import datetime

date1 = datetime.date(2026, 5, 1)
date2 = datetime.date(2026, 5, 31)

difference = date2 - date1

print(difference.days)

Output:

30

Summary

  • Python uses the datetime module for date and time operations.
  • datetime.now() returns the current date and time.
  • date.today() returns the current date.
  • strftime() formats dates and times.
  • Individual components like year, month, and day can be accessed separately.
  • Dates can be compared and subtracted to find differences.