Getting Today’s Date
The date.today() function gives the current date, useful for logging or scheduling.
from datetime import date
today = date.today()
print(today)
Creating Specific Dates
You can create any date by specifying year, month, and day, which is helpful for birthdays or deadlines.
birthday = date(2000, 5, 15)
print(birthday)
Calculating Differences
Subtracting two dates gives a timedelta, allowing you to measure durations in days.
age_days = today - birthday
print("Days since birthday:", age_days.days)
Current Date and Time
datetime.now() provides the exact current time, and strftime() formats it for display.
from datetime import datetime
now = datetime.now()
print("Now:", now)
print("Formatted:", now.strftime("%Y-%m-%d %H:%M:%S"))
Adding Time
timedelta lets you add or subtract time, making it easy to calculate future or past dates.
from datetime import timedelta
future = now + timedelta(days=10)
print("In 10 days:", future)
🎯 My Take
Python’s datetime module helps you:
- Get today’s date and current time.
- Create specific dates.
- Calculate differences between dates.
- Format timestamps for display.
- Add or subtract time easily.
Dates and times are crucial for applications like scheduling, logging, and data analysis.
Top comments (0)