β° Working with Date and Time in Python#
Dates and times are everywhereβfrom birthday reminders to scheduling apps. Python provides powerful tools to work with dates, times, and durations easily. Letβs learn how to handle date and time like a pro! π β³
1. The datetime
Module π οΈ#
Pythonβs built-in datetime
module helps you create, manipulate, and format date and time.
2. Current Date and Time π#
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
Output looks like:
Current date and time: 2025-08-19 08:30:00.123456
3. Getting Date or Time Separately πβ°#
print("Date:", now.date())
print("Time:", now.time())
4. Creating Specific Date or Time π―#
from datetime import date, time
d = date(2025, 12, 25)
t = time(14, 30, 0) # 2:30 PM
print("Date:", d)
print("Time:", t)
5. Formatting Date and Time (strftime
) ποΈ#
Convert date/time to readable strings using format codes:
Code | Meaning | Example |
---|---|---|
%Y | Year (4 digits) | 2025 |
%m | Month (01-12) | 08 |
%d | Day (01-31) | 19 |
%H | Hour (00-23) | 08 |
%M | Minute (00-59) | 30 |
%S | Second (00-59) | 00 |
Example:
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted:", formatted)
Output:
Formatted: 19-08-2025 08:30:00
6. Parsing Strings to Date (strptime
) π#
Convert a date string back to a datetime
object.
date_str = "25-12-2025"
date_obj = datetime.strptime(date_str, "%d-%m-%Y")
print("Parsed date:", date_obj)
7. Date Arithmetic with timedelta
β#
Add or subtract days, seconds, or weeks using timedelta
:
from datetime import timedelta
tomorrow = now + timedelta(days=1)
print("Tomorrow:", tomorrow)
one_week_ago = now - timedelta(weeks=1)
print("One week ago:", one_week_ago)
Practice Questions with Solutions π#
- Print the current date in
YYYY/MM/DD
format. - Calculate the date 10 days from today.
- Convert
"2025-01-01 12:00:00"
string into a datetime object and print it.
Mini Project: Countdown Timer β³#
Calculate the number of days remaining until a userβs next birthday.
from datetime import datetime
birthday_str = input("Enter your birthday (DD-MM): ")
birthday = datetime.strptime(birthday_str, "%d-%m")
now = datetime.now()
this_year_birthday = birthday.replace(year=now.year)
if this_year_birthday < now:
this_year_birthday = this_year_birthday.replace(year=now.year + 1)
days_left = (this_year_birthday - now).days
print(f"Days until your birthday: {days_left}")
Checklist for This Chapter β #
- Imported and used
datetime
module - Got current date and time
- Formatted dates using
strftime
- Parsed strings to dates with
strptime
- Done date arithmetic using
timedelta
Youβre now ready to build apps that work with dates and timesβlike calendars, reminders, and timers! Keep experimenting! π