MyInternships.in

Python Modules & Packages

Python datetime Module

The datetime module lets Python work with dates and times: getting the current date, formatting it as text, parsing text into dates, and calculating differences.


Getting the Current Date and Time

The datetime module offers two closely related classes: date, for a calendar date, and datetime, which additionally stores the time down to microseconds. Both provide a shortcut to get "right now".

Current date and datetime
Python
from datetime import date, datetime

today = date.today()
now = datetime.now()

print(today)
print(now)

Formatting Dates With strftime

strftime converts a date or datetime object into a custom text string, using format codes that stand for pieces like the year, month, or day.

Formatting with strftime
Python
now = datetime.now()
print(now.strftime("%d-%m-%Y"))
print(now.strftime("%A, %B %d, %Y"))

Parsing Text Into Dates With strptime

strptime does the reverse — it reads a text string and turns it into a real datetime object, as long as you tell it exactly what format the text is in.

Parsing with strptime
Python
text = "10-07-2026"
parsed = datetime.strptime(text, "%d-%m-%Y")
print(parsed)

Common Format Codes

CodeMeaningExample
%dDay of month (2 digits)10
%mMonth (2 digits)07
%YYear (4 digits)2026
%yYear (2 digits)26
%AFull weekday nameFriday
%BFull month nameJuly
%HHour, 24-hour clock14
%MMinute05
%SSecond09

Doing Date Math With timedelta

timedelta represents a span of time, letting you add or subtract days, hours, or minutes from a date — perfect for calculating deadlines or expiry dates.

Adding days with timedelta
Python
from datetime import timedelta

today = date.today()
next_week = today + timedelta(days=7)
print(next_week)
💡

Always match your strftime/strptime format string exactly to the data — a mismatched code, like %m vs %d, is one of the most common beginner bugs.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships