0
0
Pythonprogramming~5 mins

Date and time handling in Python

Choose your learning style9 modes available
Introduction
We use date and time handling to work with dates and clocks in programs, like showing today's date or measuring how long something takes.
Showing the current date and time on a website or app.
Calculating how many days until a birthday or event.
Measuring how long a task or game takes to finish.
Storing timestamps when users log in or save data.
Comparing two dates to check which is earlier or later.
Syntax
Python
from datetime import datetime, date, time, timedelta

# Get current date and time
now = datetime.now()

# Create a specific date
d = date(2024, 6, 1)

# Create a specific time
t = time(14, 30, 0)

# Add or subtract time
delta = timedelta(days=5)
new_date = d + delta
Use datetime.now() to get the current date and time.
Use timedelta to add or subtract days, seconds, or other time units.
Examples
Prints the current date and time.
Python
from datetime import datetime

now = datetime.now()
print(now)
Creates and prints a specific date.
Python
from datetime import date

birthday = date(1990, 12, 25)
print(birthday)
Adds 7 days to today's date and prints the new date.
Python
from datetime import timedelta, date

today = date.today()
week_later = today + timedelta(days=7)
print(week_later)
Sample Program
This program shows the current date and time, calculates a date 10 days later, and finds how many days until a birthday.
Python
from datetime import datetime, timedelta

# Get current date and time
now = datetime.now()
print(f"Current date and time: {now}")

# Calculate date 10 days from now
future_date = now + timedelta(days=10)
print(f"Date 10 days from now: {future_date.date()}")

# Calculate how many days until a specific date
birthday = datetime(2024, 12, 25)
days_until_birthday = (birthday - now).days
print(f"Days until birthday: {days_until_birthday}")
OutputSuccess
Important Notes
The datetime module helps you work with dates and times easily.
Remember that months and days start counting from 1, not 0.
Use .date() to get only the date part from a datetime object.
Summary
Date and time handling lets programs work with clocks and calendars.
Use datetime, date, time, and timedelta to create and change dates and times.
You can add or subtract days and compare dates to find differences.