Tutorials Logic
Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Dates in Python — datetime, strftime, timedelta

The datetime Module

Python's built-in datetime module provides classes for working with dates and times. The main classes are date, time, datetime, and timedelta.

Getting Current Date & Time

Current Date & Time
from datetime import date, time, datetime

# Current date
today = date.today()
print(today)           # 2024-01-15
print(today.year)      # 2024
print(today.month)     # 1
print(today.day)       # 15

# Current date and time
now = datetime.now()
print(now)             # 2024-01-15 14:30:45.123456
print(now.hour)        # 14
print(now.minute)      # 30
print(now.second)      # 45

# UTC time
from datetime import timezone
utc_now = datetime.now(timezone.utc)
print(utc_now)

Creating Date & Time Objects

Creating Objects
from datetime import date, time, datetime

# Specific date
birthday = date(1990, 6, 15)
print(birthday)         # 1990-06-15

# Specific time
alarm = time(7, 30, 0)
print(alarm)            # 07:30:00

# Specific datetime
event = datetime(2024, 12, 25, 18, 0, 0)
print(event)            # 2024-12-25 18:00:00

# From timestamp (Unix time)
import time as t
ts = datetime.fromtimestamp(t.time())
print(ts)

# From ISO format string
dt = datetime.fromisoformat("2024-06-15T14:30:00")
print(dt)

Formatting Dates (strftime)

Use strftime() to format a datetime as a string.

strftime - Format Codes
from datetime import datetime

now = datetime(2024, 6, 15, 14, 30, 45)

print(now.strftime("%Y-%m-%d"))           # 2024-06-15
print(now.strftime("%d/%m/%Y"))           # 15/06/2024
print(now.strftime("%B %d, %Y"))          # June 15, 2024
print(now.strftime("%A, %B %d, %Y"))      # Saturday, June 15, 2024
print(now.strftime("%I:%M %p"))           # 02:30 PM
print(now.strftime("%H:%M:%S"))           # 14:30:45
print(now.strftime("%Y-%m-%dT%H:%M:%S"))  # ISO 8601

# Common format codes:
# %Y = 4-digit year    %m = month (01-12)   %d = day (01-31)
# %H = hour (00-23)    %M = minute (00-59)  %S = second (00-59)
# %I = hour (01-12)    %p = AM/PM           %A = weekday name
# %B = month name      %j = day of year     %W = week number

Parsing Dates (strptime)

strptime - Parse Strings
from datetime import datetime

# Parse a date string into a datetime object
dt = datetime.strptime("2024-06-15", "%Y-%m-%d")
print(dt)           # 2024-06-15 00:00:00

dt2 = datetime.strptime("June 15, 2024 2:30 PM", "%B %d, %Y %I:%M %p")
print(dt2)          # 2024-06-15 14:30:00

# Convert between formats
user_input = "15/06/2024"
parsed = datetime.strptime(user_input, "%d/%m/%Y")
formatted = parsed.strftime("%B %d, %Y")
print(formatted)    # June 15, 2024

Date Arithmetic with timedelta

timedelta
from datetime import date, datetime, timedelta

today = date.today()

# Add/subtract days
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
next_month = today + timedelta(days=30)

print(tomorrow)     # tomorrow's date
print(last_week)    # 7 days ago
print(next_month)   # 30 days from now

# Difference between two dates
start = date(2024, 1, 1)
end = date(2024, 12, 31)
diff = end - start
print(diff.days)    # 365

# Age calculator
birthday = date(1990, 6, 15)
today = date.today()
age = today.year - birthday.year
if (today.month, today.day) < (birthday.month, birthday.day):
    age -= 1
print(f"Age: {age}")

# Time difference
start_time = datetime(2024, 1, 1, 9, 0, 0)
end_time = datetime(2024, 1, 1, 17, 30, 0)
duration = end_time - start_time
print(duration)              # 8:30:00
print(duration.seconds)      # 30600 seconds
print(duration.seconds // 3600)  # 8 hours

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.