Python provides the datetime module for working with dates, times, and date-time values.
It is useful for:
- Getting the current date and time
- Creating dates
- Creating times
- Formatting dates
- Comparing dates
- Calculating differences between dates
- Adding and subtracting time
- Working with timestamps
- Handling birthdays, deadlines, bookings, and schedules
Import the datetime Module
import datetimePython's datetime module provides several important classes:
date → Work with dates
time → Work with time
datetime → Work with date + time
timedelta → Calculate differences between dates/timesGet the Current Date
from datetime import date
today = date.today()
print(today)Output:
2026-09-01The exact output depends on the day the program runs.
Get the Current Date and Time
from datetime import datetime
now = datetime.now()
print(now)Example output:
2026-09-01 23:08:15.452381The result contains:
Year-Month-Day Hour:Minute:SecondGet Only the Current Time
from datetime import datetime
current_time = datetime.now().time()
print(current_time)Example output:
23:08:15.452381Create a Specific Date
You can create a date using date().
from datetime import date
birthday = date(2000, 5, 15)
print(birthday)Output:
2000-05-15The order is:
date(year, month, day)Create a Specific Time
Use the time() class.
from datetime import time
meeting_time = time(10, 30, 0)
print(meeting_time)Output:
10:30:00The format is:
time(hour, minute, second)Create a Specific Date and Time
Use datetime().
from datetime import datetime
meeting = datetime(
2026,
9,
15,
10,
30
)
print(meeting)Output:
2026-09-15 10:30:00Access Date Components
You can access individual parts of a date.
from datetime import datetime
now = datetime.now()
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)Example output:
Year: 2026
Month: 9
Day: 1Access Time Components
from datetime import datetime
now = datetime.now()
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)Example output:
Hour: 23
Minute: 8
Second: 15Get the Day of the Week
The weekday() method returns a number from 0 to 6.
from datetime import date
today = date.today()
print(today.weekday())The values are:
0 → Monday
1 → Tuesday
2 → Wednesday
3 → Thursday
4 → Friday
5 → Saturday
6 → SundayGet the Day Name
You can use strftime() to get the day name.
from datetime import date
today = date.today()
print(today.strftime("%A"))Example output:
TuesdayGet the Short Day Name
from datetime import date
today = date.today()
print(today.strftime("%a"))Example output:
TueGet the Month Name
from datetime import date
today = date.today()
print(today.strftime("%B"))Example output:
SeptemberGet the Short Month Name
from datetime import date
today = date.today()
print(today.strftime("%b"))Example output:
SepFormat a Date with strftime()
strftime() converts a date or datetime object into a formatted string.
from datetime import datetime
now = datetime.now()
formatted = now.strftime(
"%d-%m-%Y"
)
print(formatted)Example output:
01-09-2026Common strftime() Codes
%Y → Full year 2026
%y → Short year 26
%m → Month number 09
%B → Full month September
%b → Short month Sep
%d → Day 01
%A → Full day Tuesday
%a → Short day Tue
%H → Hour (24-hour) 23
%I → Hour (12-hour) 11
%M → Minute 08
%S → Second 15
%p → AM/PM PMFormat Date and Time
from datetime import datetime
now = datetime.now()
formatted = now.strftime(
"%d-%m-%Y %H:%M:%S"
)
print(formatted)Example output:
01-09-2026 23:08:1512-Hour Time Format
Use %I and %p.
from datetime import datetime
now = datetime.now()
formatted = now.strftime(
"%d-%m-%Y %I:%M:%S %p"
)
print(formatted)Example output:
01-09-2026 11:08:15 PMConvert String to Date with strptime()
strptime() converts a string into a datetime object.
from datetime import datetime
date_string = "15-09-2026"
date_object = datetime.strptime(
date_string,
"%d-%m-%Y"
)
print(date_object)Output:
2026-09-15 00:00:00Convert String to Date
If you only need a date object:
from datetime import datetime
date_string = "15-09-2026"
date_object = datetime.strptime(
date_string,
"%d-%m-%Y"
).date()
print(date_object)Output:
2026-09-15strftime() vs strptime()
These two methods are easy to confuse.
strftime()
↓
datetime → stringstrptime()
↓
string → datetimeExample:
from datetime import datetime
now = datetime.now()
text = now.strftime("%d-%m-%Y")
date_object = datetime.strptime(
text,
"%d-%m-%Y"
)
print(text)
print(date_object)Compare Two Dates
Python allows you to compare date objects.
from datetime import date
date1 = date(2026, 9, 1)
date2 = date(2026, 9, 15)
print(date1 < date2)
print(date1 > date2)
print(date1 == date2)Output:
True
False
FalseCheck Whether a Date Has Passed
from datetime import date
today = date.today()
deadline = date(2026, 8, 20)
if today > deadline:
print("Deadline has passed")
else:
print("Deadline is still available")Calculate Difference Between Dates
Use timedelta or subtract two dates.
from datetime import date
start = date(2026, 9, 1)
end = date(2026, 9, 15)
difference = end - start
print(difference)Output:
14 days, 0:00:00Get Difference in Days
from datetime import date
start = date(2026, 9, 1)
end = date(2026, 9, 15)
difference = end - start
print(difference.days)Output:
14Using timedelta
timedelta represents a duration.
from datetime import timedelta
duration = timedelta(days=10)
print(duration)Output:
10 days, 0:00:00Add Days to a Date
from datetime import date, timedelta
today = date.today()
future_date = today + timedelta(days=7)
print("Today:", today)
print("After 7 days:", future_date)Subtract Days from a Date
from datetime import date, timedelta
today = date.today()
previous_date = today - timedelta(days=7)
print("Today:", today)
print("7 days ago:", previous_date)Add Weeks
from datetime import date, timedelta
today = date.today()
future_date = today + timedelta(weeks=4)
print(future_date)Add Hours
timedelta can also work with hours.
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(hours=5)
print(future)Add Minutes
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(minutes=30)
print(future)Add Seconds
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(seconds=45)
print(future)Calculate Age
You can calculate an approximate age using dates.
from datetime import date
birth_date = date(2000, 5, 15)
today = date.today()
age = today.year - birth_date.year
if (today.month, today.day) < (
birth_date.month,
birth_date.day
):
age -= 1
print("Age:", age)Calculate Days Until a Date
from datetime import date
today = date.today()
event_date = date(2026, 12, 25)
days_left = (event_date - today).days
print("Days left:", days_left)Practical Example : Course Deadline
from datetime import date
today = date.today()
deadline = date(2026, 9, 30)
days_left = (deadline - today).days
if days_left > 0:
print(
"Days remaining:",
days_left
)
elif days_left == 0:
print("Deadline is today")
else:
print("Deadline has passed")Practical Example : Student Assignment
from datetime import date
submission_date = date(2026, 9, 10)
today = date.today()
if today <= submission_date:
remaining = (
submission_date - today
).days
print(
"Days remaining:",
remaining
)
else:
print("Assignment deadline passed")Practical Example : Booking Date
from datetime import datetime
booking = datetime(
2026,
9,
20,
14,
30
)
print(
booking.strftime(
"%d %B %Y at %I:%M %p"
)
)Output:
20 September 2026 at 02:30 PMPractical Example : Generate Dates
You can use timedelta with a loop.
from datetime import date, timedelta
start = date(2026, 9, 1)
for i in range(7):
current = start + timedelta(days=i)
print(current)Output:
2026-09-01
2026-09-02
2026-09-03
2026-09-04
2026-09-05
2026-09-06
2026-09-07Practical Example : Generate Formatted Dates
from datetime import date, timedelta
start = date(2026, 9, 1)
for i in range(7):
current = start + timedelta(days=i)
print(
current.strftime(
"%d-%m-%Y"
)
)Practical Example : Find Weekend
from datetime import date
today = date.today()
if today.weekday() >= 5:
print("Weekend")
else:
print("Weekday")Here:
5 → Saturday
6 → SundayPractical Example : Check Birth Month
from datetime import date
birth_date = date(2000, 5, 15)
today = date.today()
if birth_date.month == today.month:
print("Birthday month!")
else:
print("Not the birthday month")Practical Example : Calculate Working Days
A simple example can exclude Saturday and Sunday.
from datetime import date, timedelta
start = date(2026, 9, 1)
end = date(2026, 9, 10)
working_days = 0 current = start
while current <= end:
if current.weekday() < 5:
working_days += 1
current += timedelta(days=1)
print("Working days:", working_days)Timestamp
A timestamp represents a point in time as the number of seconds relative to the Unix epoch.
You can get the current timestamp using:
from datetime import datetime
timestamp = datetime.now().timestamp()
print(timestamp)Example output:
1788275295.452381The exact value changes continuously.
Convert Timestamp to Date and Time
from datetime import datetime
timestamp = 1788275295
result = datetime.fromtimestamp(
timestamp
)
print(result)Date Formatting for Websites
When developing websites, dates often need to be displayed in a user-friendly format.
from datetime import datetime
date_value = datetime.now()
print(
date_value.strftime(
"%B %d, %Y"
)
)Example output:
September 01, 2026Another format:
print(
date_value.strftime(
"%d %b %Y"
)
)Example output:
01 Sep 2026Important Methods and Classes
date.today() → Current date
datetime.now() → Current date and time
datetime.date() → Get date from datetime
datetime.time() → Get time from datetime
strftime() → Date/time → string
strptime() → String → datetime
weekday() → Day number
timedelta() → Time duration
timestamp() → Convert to timestamp
fromtimestamp() → Timestamp → datetimeDate and Time Cheat Sheet
from datetime import date, datetime, timedeltaCurrent date:
date.today()Current date and time:
datetime.now()Create date:
date(2026, 9, 1)Create datetime:
datetime(2026, 9, 1, 10, 30)Format date:
datetime.now().strftime("%d-%m-%Y")Convert string:
datetime.strptime(
"01-09-2026",
"%d-%m-%Y"
)Add days:
datetime.now() + timedelta(days=7)Subtract days:
datetime.now() - timedelta(days=7)Difference:
date2 - date1Important Points to Remember
date
↓
Only date
time
↓
Only time
datetime
↓
Date + time
timedelta
↓
Difference/durationAnd remember:
strftime() → datetime to string
strptime() → string to datetimeMini Practice
Try solving these yourself:
from datetime import date, datetime, timedelta
# 1. Print today's date
# 2. Print current date and time
# 3. Create your birth date
# 4. Calculate your age
# 5. Calculate the date after 30 days
# 6. Calculate the date 30 days ago
# 7. Calculate days between two dates
# 8. Display today's date as: # 01 September 2026
# 9. Check whether today is a weekend
# 10. Find how many days remain until # a given deadline