Skip to content

Dates and 次数

工作使用 dates and 次数 using datetime, timedelta, 格式化, timezones, and parsing.

你将学到

  • 创建 date, 时间, and datetime 对象
  • 执行 arithmetic 使用 timedelta
  • 格式 and parse dates 使用 strftime and strptime
  • Handle timezones 使用 zoneinfo
  • Calculate durations and compare dates

概念讲解

The datetime Module

The datetime module is Python's standard library for date and time manipulation. It provides four main types:

  • date — year, month, day (no time)
  • 时间 — hour, minute, second, microsecond (no date)
  • datetime — both date and time
  • timedelta — a duration (difference between two datetimes)
from datetime import date, time, datetime, timedelta

today = date.today()               # 2024-01-15
now = datetime.now()               # 2024-01-15 14:30:45.123456
specific = date(2024, 7, 4)        # July 4, 2024
moment = datetime(2024, 7, 4, 12, 0, 0)  # July 4, 2024 at noon

Creating Date and Time Objects

from datetime import date, time, datetime

# date — just a calendar date
d = date(2024, 1, 15)
print(d.year, d.month, d.day)  # 2024 1 15

# time — just a clock time (no date)
t = time(14, 30, 45)
print(t.hour, t.minute, t.second)  # 14 30 45

# datetime — both date and time
dt = datetime(2024, 1, 15, 14, 30, 45)
print(dt)  # 2024-01-15 14:30:45

# From a timestamp (Unix epoch)
from_timestamp = datetime.fromtimestamp(1705312200)

Formatting and Parsing

Use strftime() (string format time) to convert to a string, and strptime() (string parse time) to parse from a string:

from datetime import datetime

dt = datetime(2024, 1, 15, 14, 30, 45)

# Format to string
print(dt.strftime("%Y-%m-%d"))        # 2024-01-15
print(dt.strftime("%B %d, %Y"))       # January 15, 2024
print(dt.strftime("%H:%M:%S"))        # 14:30:45
print(dt.strftime("%Y-%m-%d %H:%M"))  # 2024-01-15 14:30

# Parse from string
parsed = datetime.strptime("2024-01-15", "%Y-%m-%d")
print(parsed)  # 2024-01-15 00:00:00

Common format codes: | Code | Meaning | Example | |------|---------|---------| | %Y | 4-digit year | 2024 | | %m | 2-digit month | 01 | | %d | 2-digit day | 15 | | %H | hour (24h) | 14 | | %M | minute | 30 | | %S | second | 45 | | %B | full month name | January | | %b | abbreviated month | Jan | | % | full weekday | Monday | | %I | hour (12h) | 02 | | %p | AM/PM | PM |

timedelta — Date Arithmetic

timedelta represents a duration. You can add and subtract it from dates:

from datetime import date, timedelta

today = date.today()
one_week = timedelta(weeks=1)
yesterday = today - timedelta(days=1)
next_week = today + one_week

# Differences between dates produce timedelta
diff = date(2024, 12, 31) - date(2024, 1, 1)
print(diff.days)  # 365

# timedelta components
td = timedelta(days=2, hours=6, minutes=30)
print(td.total_seconds())  # 198000.0
from datetime import datetime, timedelta

now = datetime.now()
future = now + timedelta(days=30, hours=12)
past = now - timedelta(weeks=2)

print(f"现在: {现在}")
print(f"30 days 12 hours later: {future}")
print(f"2 weeks ago: {past}")

# Difference between two datetimes
duration = future - now
print(f"Duration: {duration}")  # 30 days, 12:00:00
print(f"总计 seconds: {duration.total_seconds()}")

Comparing Dates

Dates and datetimes support comparison operators:

from datetime import date

d1 = date(2024, 1, 15)
d2 = date(2024, 7, 4)

print(d1 < d2)   # True
print(d1 == d1)  # True
print(max(d1, d2))  # 2024-07-04

# Check if a date is in a range
start = date(2024, 1, 1)
end = date(2024, 12, 31)
print(start <= d1 <= end)  # True

Timezones

Python 3.9+ includes zoneinfo for timezone support:

from datetime import datetime
from zoneinfo import ZoneInfo

# Create timezone-aware datetimes
utc_now = datetime.now(ZoneInfo("UTC"))
tokyo_now = datetime.now(ZoneInfo("Asia/Tokyo"))
ny_now = datetime.now(ZoneInfo("America/New_York"))

print(f"UTC: {utc_now}")
print(f"Tokyo: {tokyo_now}")
print(f"新 York: {ny_now}")

# Convert between timezones
tokyo_time = utc_now.astimezone(ZoneInfo("Asia/Tokyo"))

Always use timezone-aware datetimes in applications — naive datetimes (without timezone info) are a common source of bugs. Use datetime.now(ZoneInfo("UTC")) instead of datetime.now().

Practical Examples

from datetime import datetime, timedelta

# Age calculation
def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    # Adjust if birthday hasn't occurred this year
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        age -= 1
    return age

# Days until a target date
def days_until(target):
    return (target - date.today()).days

示例代码

              from datetime import date, time, datetime, timedelta

# Creating objects
today = date.today()
now = datetime.now()
specific = datetime(2024, 7, 4, 12, 0, 0)
print(f"Today: {today}")
print(f"Now: {now}")
print(f"Specific: {specific}")

# Formatting
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%B %d, %Y at %I:%M %p"))

# Parsing
parsed = datetime.strptime("2024-12-25", "%Y-%m-%d")
print(f"Parsed Christmas: {parsed}")

# timedelta arithmetic
one_week_later = today + timedelta(weeks=1)
yesterday = today - timedelta(days=1)
print(f"One week later: {one_week_later}")
print(f"Yesterday: {yesterday}")

# Difference between dates
diff = date(2024, 12, 31) - date(2024, 1, 1)
print(f"Days in 2024: {diff.days}")

# Comparing dates
d1, d2 = date(2024, 1, 15), date(2024, 7, 4)
print(f"d1 < d2: {d1 < d2}")
print(f"Max: {max(d1, d2)}")

# Age calculation
def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        age -= 1
    return age

ada_birthday = date(1815, 12, 10)
print(f"Ada Lovelace would be: {calculate_age(ada_birthday)}")

# Timezone (Python 3.9+)
from zoneinfo import ZoneInfo
utc = datetime.now(ZoneInfo("UTC"))
tokyo = utc.astimezone(ZoneInfo("Asia/Tokyo"))
print(f"UTC: {utc.strftime('%H:%M')}")
print(f"Tokyo: {tokyo.strftime('%H:%M')}")
            

Shows 创建 date/datetime 对象, 格式化使用 strftime, parsing 使用 strptime, timedelta arithmetic, date comparison, age calculation 函数, and timezone conversion 之间 UTC and Tokyo.

动手试一试

  • JSON Formatter

    Dates 是经常 serialized 到 JSON — ISO 格式字符串是 标准.

  • 文本计数器

    Timestamps in logs 是 parsed and analyzed 使用 datetime.

常见错误

错误写法

Using naive datetimes (不使用 timezone) and 获取错误 results 跨越 timezones

正确做法

总是 use timezone-aware datetimes: datetime.现在(ZoneInfo('UTC')) 相反的 datetime.现在(). Naive datetimes silently produce 错误 results 当 compared or converted 跨越 timezones. Use zoneinfo (Python 3.9+) for timezone support.

错误写法

Confusing strftime (格式到 字符串) 使用 strptime (parse 从字符串)

正确做法

strftime = 字符串 FROM 时间 (datetime → 字符串). strptime = 字符串 PARSE 时间 (字符串 → datetime). 'f' in strftime stands for '格式', 'p' in strptime stands for 'parse'. Remember: strftime 输出, strptime 输入.

相关速查表

练习 Dates and 次数

1 个练习

练习 Dates and 次数

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误