Dates and Times

Handling dates and times is one of the most common tasks in programming — recording log timestamps, calculating borrowing days, aggregating data over time periods... The datetime module is Python's standard way of working with dates and times.


1. Getting the Current Time

PYTHON
from datetime import datetime, date, time

# Current datetime
now = datetime.now()
print(now)                      # 2026-06-23 16:00:00.123456

# Current date
today = date.today()
print(today)                    # 2026-06-23

# Create a specific date
d = datetime(2026, 6, 23, 15, 30, 0)
print(d)                        # 2026-06-23 15:30:00

Example: Birthday Reminder (Difficulty: Star)

PYTHON
from datetime import datetime

def days_to_birthday(birth_str):
    """Calculate days until next birthday"""
    today = datetime.now()
    birth = datetime.strptime(birth_str, "%m-%d")
    birthday_this_year = birth.replace(year=today.year)

    if birthday_this_year < today:
        birthday_this_year = birthday_this_year.replace(year=today.year + 1)

    delta = birthday_this_year - today
    return delta.days

print(f"Days until next birthday: {days_to_birthday('12-25')}")
▶ Try it Yourself

2. Formatting and Parsing

PYTHON
from datetime import datetime

# Date -> string (formatting)
now = datetime.now()
print(now.strftime("%Y-%m-%d"))              # 2026-06-23
print(now.strftime("%Y-%m-%d"))              # 2026-06-23
print(now.strftime("%H:%M:%S"))              # 16:00:00
print(now.strftime("%A"))                    # Tuesday

# String -> date (parsing)
date_str = "2026-06-23 15:30:00"
parsed = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed)                                # 2026-06-23 15:30:00
Format Code Meaning Example
%Y 4-digit year 2026
%m 2-digit month 06
%d 2-digit day 23
%H Hour (24-hour) 15
%M Minute 30
%S Second 00
%A Full weekday name Tuesday

Tip: strftime is "date -> string", strptime is "string -> date". Remember: "f" = format (output), "p" = parse (input).


3. timedelta: Time Differences

PYTHON
from datetime import datetime, timedelta

now = datetime.now()

# Calculate future/past times
future = now + timedelta(days=7)
past = now - timedelta(days=30)

print(f"In 7 days: {future.strftime('%Y-%m-%d')}")
print(f"30 days ago: {past.strftime('%Y-%m-%d')}")

# Time calculation
print(timedelta(days=7))                     # 7 days, 0:00:00
print(timedelta(hours=3, minutes=15))        # 3:15:00
print(timedelta(weeks=2))                    # 14 days, 0:00:00

# Subtract two dates
d1 = datetime(2026, 6, 1)
d2 = datetime(2026, 6, 23)
diff = d2 - d1
print(f"Difference: {diff.days} days")       # Difference: 22 days

Example: Subscription Expiry Reminder (Difficulty: Star-Star)

PYTHON
from datetime import datetime, timedelta

# Simulate user subscription info
subscriptions = [
    {"name": "Zhang San", "expire": "2026-07-15"},
    {"name": "Li Si", "expire": "2026-06-25"},
    {"name": "Wang Wu", "expire": "2026-08-01"},
    {"name": "Zhao Liu", "expire": "2026-06-20"},
]

today = datetime.now().strftime("%Y-%m-%d")
today = datetime.strptime(today, "%Y-%m-%d")

print("=== Subscription Expiry Check ===")
for sub in subscriptions:
    expire = datetime.strptime(sub["expire"], "%Y-%m-%d")
    remaining = (expire - today).days

    if remaining < 0:
        print(f"Expired ({sub['name']}): {-remaining} days ago")
    elif remaining <= 7:
        print(f"Expiring soon ({sub['name']}): {remaining} days left")
    else:
        print(f"Active ({sub['name']}): {remaining} days left")
▶ Try it Yourself

Common Use Cases


FAQ

Q Does datetime.now() return local time or UTC time?
A Local time. Use datetime.utcnow() for UTC. Note that utcnow() returns a naive datetime without timezone info. For production, use datetime.now(timezone.utc) or pytz/zoneinfo for proper timezone handling.
Q What happens if strptime parsing fails?
A It raises ValueError — "time data 'xxx' does not match format '%Y-%m-%d'". Wrap it in try-except to handle errors. Common pitfall: months and days must be two digits (%m won't match "6", it needs "06").
Q What's the maximum days supported by timedelta?
A Theoretically no upper limit — timedelta(days=1000000) is valid. However, total_seconds() might overflow. For everyday use, range is not a concern.

Summary


Exercises

  1. Beginner (Difficulty: Star): Output the current time in these formats: 2026-06-23 Tuesday, 2026-06-23 16:00, 06/23/2026.

  2. Intermediate (Difficulty: Star-Star): Write a function workdays_between(start, end) that calculates how many weekdays (Monday to Friday) there are between two dates. Hint: Use timedelta to iterate each day; use weekday() to check the day of the week (0=Monday, 4=Friday).

  3. Advanced (Difficulty: Star-Star-Star): Write a "Pomodoro Timer." Work 25 minutes -> rest 5 minutes, loop 4 times, then take a long rest of 15 minutes. Use time.sleep() for timing and datetime to display the current phase and remaining time.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏