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.
Jump into concepts and practice - no test required
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
datetime.now() to get the current date and time.timedelta to add or subtract days, seconds, or other time units.from datetime import datetime now = datetime.now() print(now)
from datetime import date birthday = date(1990, 12, 25) print(birthday)
from datetime import timedelta, date today = date.today() week_later = today + timedelta(days=7) print(week_later)
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}")
datetime module helps you work with dates and times easily..date() to get only the date part from a datetime object.datetime, date, time, and timedelta to create and change dates and times.datetime module provides classes for manipulating dates and times.math is for math functions, random for random numbers, os for operating system tasks.date class constructor takes year, month, day as integers in that order.datetime.date(2024, 1, 1). date = datetime(2024, 1, 1) misses .date. date = datetime.date('2024-01-01') passes a string, which is invalid. date = datetime.date(1, 1, 2024) has wrong argument order.from datetime import date, timedelta start = date(2024, 4, 25) new_date = start + timedelta(days=10) print(new_date)
timedelta(days=10) to April 25, 2024 adds 10 days.from datetime import datetime dt = datetime(2024, 2, 30) print(dt)
date objects gives a timedelta representing the difference..days attribute to get the number of days between dates.