datetime模块是Python中处理日期和时间的标准工具。它可以获取当前时间、创建特定日期、计算时间差,还能格式化日期时间显示。
from datetime import datetime
# 获取当前日期和时间
now = datetime.now()
print("当前时间:", now)
# 分别获取日期部分和时间部分
print("日期:", now.date())
print("时间:", now.time())
print("年份:", now.year)
print("月份:", now.month)
print("日期:", now.day)
print("小时:", now.hour)
print("分钟:", now.minute)
print("秒:", now.second)from datetime import datetime, date, time
# 创建完整的日期时间对象
new_year = datetime(2024, 1, 1, 0, 0, 0)
print("2024年元旦:", new_year)
# 只创建日期
birthday = date(1990, 5, 15)
print("生日日期:", birthday)
# 只创建时间
meeting_time = time(14, 30, 0)
print("会议时间:", meeting_time)from datetime import datetime
now = datetime.now()
# 常用格式化方式
print("默认格式:", now)
print("ISO格式:", now.isoformat())
print("年月日:", now.strftime("%Y-%m-%d"))
print("中文格式:", now.strftime("%Y年%m月%d日"))
print("详细时间:", now.strftime("%H时%M分%S秒"))
print("完整格式:", now.strftime("%Y-%m-%d %H:%M:%S"))
print("星期:", now.strftime("%A")) # 英文星期
print("简写星期:", now.strftime("%a")) # 英文星期简写from datetime import datetime
# 从字符串解析日期时间
date_str = "2024-01-20 15:30:00"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("解析结果:", dt)
# 解析不同格式的日期
formats = [
("20/01/2024", "%d/%m/%Y"),
("2024年1月20日", "%Y年%m月%d日"),
("Jan 20, 2024", "%b %d, %Y")
]
for date_str, format_str in formats:
dt = datetime.strptime(date_str, format_str)
print(f"{date_str} -> {dt}")from datetime import datetime, timedelta
# 当前时间
now = datetime.now()
print("现在:", now)
# 计算未来时间
one_week_later = now + timedelta(days=7)
three_hours_later = now + timedelta(hours=3)
print("一周后:", one_week_later)
print("三小时后:", three_hours_later)
# 计算过去时间
yesterday = now - timedelta(days=1)
two_weeks_ago = now - timedelta(weeks=2)
print("昨天:", yesterday)
print("两周前:", two_weeks_ago)
# 复杂时间计算
future = now + timedelta(
days=5,
hours=3,
minutes=30,
seconds=45
)
print("5天3小时30分45秒后:", future)from datetime import datetime, date
# 创建几个日期进行比较
date1 = date(2024, 1, 15)
date2 = date(2024, 1, 20)
date3 = date(2024, 1, 25)
print(f"日期1: {date1}")
print(f"日期2: {date2}")
print(f"日期3: {date3}")
# 比较操作
print(f"日期1 < 日期2: {date1 < date2}")
print(f"日期2 > 日期3: {date2 > date3}")
print(f"日期1 == 日期2: {date1 == date2}")
# 计算日期差
date_diff = date2 - date1
print(f"日期2和日期1相差: {date_diff.days} 天")from datetime import date, timedelta
def calculate_age(birth_date):
"""计算年龄"""
today = date.today()
age = today.year - birth_date.year
# 如果今年生日还没过,年龄减1
if today < date(today.year, birth_date.month, birth_date.day):
age -= 1
return age
def days_until_birthday(birth_date):
"""计算距离下次生日的天数"""
today = date.today()
next_birthday = date(today.year, birth_date.month, birth_date.day)
# 如果今年生日已经过了,计算明年的生日
if today > next_birthday:
next_birthday = date(today.year + 1, birth_date.month, birth_date.day)
days_left = (next_birthday - today).days
return days_left
# 测试生日计算
birthday = date(1990, 5, 15)
age = calculate_age(birthday)
days_left = days_until_birthday(birthday)
print(f"出生日期: {birthday}")
print(f"当前年龄: {age}岁")
print(f"距离下次生日还有: {days_left}天")from datetime import date, timedelta
def calculate_workdays(start_date, end_date):
"""计算两个日期之间的工作日数量(排除周末)"""
workdays = 0
current_date = start_date
while current_date <= end_date:
# 周一至周五是工作日
if current_date.weekday() < 5: # 0=周一, 4=周五
workdays += 1
current_date += timedelta(days=1)
return workdays
def add_workdays(start_date, workdays_to_add):
"""在起始日期上添加指定工作日"""
current_date = start_date
workdays_added = 0
while workdays_added < workdays_to_add:
current_date += timedelta(days=1)
if current_date.weekday() < 5: # 工作日
workdays_added += 1
return current_date
# 测试工作日计算
start = date(2024, 1, 15) # 周一
end = date(2024, 1, 25) # 周四
total_workdays = calculate_workdays(start, end)
print(f"从 {start} 到 {end} 的工作日数量: {total_workdays}")
# 添加10个工作日
new_date = add_workdays(start, 10)
print(f"{start} 加上10个工作日是: {new_date}")from datetime import datetime
# 获取当前时间戳
current_timestamp = datetime.now().timestamp()
print(f"当前时间戳: {current_timestamp}")
# 时间戳转日期时间
timestamp = 1705734000 # 2024年1月20日 12:00:00
dt_from_timestamp = datetime.fromtimestamp(timestamp)
print(f"时间戳 {timestamp} 对应的日期时间: {dt_from_timestamp}")
# 日期时间转时间戳
dt = datetime(2024, 1, 20, 12, 0, 0)
timestamp_from_dt = dt.timestamp()
print(f"日期时间 {dt} 对应的时间戳: {timestamp_from_timestamp}")from datetime import datetime
import time
def measure_execution_time(func):
"""测量函数执行时间"""
start_time = datetime.now()
# 执行函数
func()
end_time = datetime.now()
execution_time = end_time - start_time
print(f"函数执行时间: {execution_time}")
return execution_time
# 测试函数
def slow_function():
"""模拟耗时操作"""
time.sleep(2) # 休眠2秒
# 测量执行时间
execution_time = measure_execution_time(slow_function)
print(f"总秒数: {execution_time.total_seconds():.2f}秒")from datetime import datetime
def is_valid_date(year, month, day):
"""检查日期是否有效"""
try:
datetime(year, month, day)
return True
except ValueError:
return False
def is_valid_time(hour, minute, second):
"""检查时间是否有效"""
try:
datetime(2000, 1, 1, hour, minute, second) # 使用任意有效日期
return True
except ValueError:
return False
# 测试日期时间验证
test_dates = [
(2024, 2, 29), # 闰年,有效
(2023, 2, 29), # 非闰年,无效
(2024, 13, 1), # 无效月份
(2024, 1, 32), # 无效日期
]
for year, month, day in test_dates:
valid = is_valid_date(year, month, day)
print(f"{year}-{month:02d}-{day:02d}: {'有效' if valid else '无效'}")
# 测试时间验证
test_times = [
(23, 59, 59), # 有效
(24, 0, 0), # 无效
(12, 60, 0), # 无效
]
for hour, minute, second in test_times:
valid = is_valid_time(hour, minute, second)
print(f"{hour:02d}:{minute:02d}:{second:02d}: {'有效' if valid else '无效'}")from datetime import datetime, timezone, timedelta
# 创建时区对象
beijing_tz = timezone(timedelta(hours=8)) # 北京时间 UTC+8
newyork_tz = timezone(timedelta(hours=-5)) # 纽约时间 UTC-5
# 带时区的当前时间
utc_now = datetime.now(timezone.utc)
beijing_now = datetime.now(beijing_tz)
print(f"UTC时间: {utc_now}")
print(f"北京时间: {beijing_now}")
# 时区转换
utc_time = datetime(2024, 1, 20, 12, 0, 0, tzinfo=timezone.utc)
beijing_time = utc_time.astimezone(beijing_tz)
newyork_time = utc_time.astimezone(newyork_tz)
print(f"UTC时间: {utc_time}")
print(f"北京时间: {beijing_time}")
print(f"纽约时间: {newyork_time}")from datetime import date, timedelta
def generate_date_range(start_date, end_date):
"""生成日期范围内的所有日期"""
current_date = start_date
dates = []
while current_date <= end_date:
dates.append(current_date)
current_date += timedelta(days=1)
return dates
def get_week_dates(target_date):
"""获取目标日期所在周的所有日期"""
# 找到周一的日期
start_of_week = target_date - timedelta(days=target_date.weekday())
# 生成一周的日期
week_dates = []
for i in range(7):
week_dates.append(start_of_week + timedelta(days=i))
return week_dates
# 测试日期范围
start = date(2024, 1, 1)
end = date(2024, 1, 7)
date_range = generate_date_range(start, end)
print("2024年第一周的日期:")
for d in date_range:
print(f" {d} ({d.strftime('%A')})")
# 测试获取周日期
today = date.today()
this_week = get_week_dates(today)
print(f"\n本周日期:")
for d in this_week:
day_name = "周一" if d.weekday() == 0 else \
"周二" if d.weekday() == 1 else \
"周三" if d.weekday() == 2 else \
"周四" if d.weekday() == 3 else \
"周五" if d.weekday() == 4 else \
"周六" if d.weekday() == 5 else "周日"
print(f" {d} ({day_name})")from datetime import datetime
class DateFormatter:
"""日期格式化工具类"""
@staticmethod
def format_chinese(dt):
"""中文格式"""
return dt.strftime("%Y年%m月%d日 %H时%M分%S秒")
@staticmethod
def format_iso(dt):
"""ISO格式"""
return dt.isoformat()
@staticmethod
def format_readable(dt):
"""易读格式"""
return dt.strftime("%A, %B %d, %Y at %I:%M %p")
@staticmethod
def format_filename(dt):
"""文件名格式"""
return dt.strftime("%Y%m%d_%H%M%S")
@staticmethod
def format_database(dt):
"""数据库格式"""
return dt.strftime("%Y-%m-%d %H:%M:%S")
# 使用格式化工具
now = datetime.now()
formatter = DateFormatter()
print("中文格式:", formatter.format_chinese(now))
print("ISO格式:", formatter.format_iso(now))
print("易读格式:", formatter.format_readable(now))
print("文件名格式:", formatter.format_filename(now))
print("数据库格式:", formatter.format_database(now))| 类 | 说明 | 示例 |
|---|---|---|
| datetime.date | 日期类(年、月、日) | date(2023, 5, 15) |
| datetime.time | 时间类(时、分、秒、微秒) | time(14, 30, 0) |
| datetime.datetime | 日期时间类(包含日期和时间) | datetime(2023, 5, 15, 14, 30) |
| datetime.timedelta | 时间间隔类(用于日期/时间计算) | timedelta(days=5) |
| datetime.tzinfo | 时区信息基类(需子类化实现) | 自定义时区类 |
| 方法/属性 | 说明 | 示例 |
|---|---|---|
| date.today() | 返回当前本地日期 | date.today() → date(2023, 5, 15) |
| date.fromisoformat(str) | 从 YYYY-MM-DD 字符串解析日期 | date.fromisoformat("2023-05-15") |
| date.year | 年份(只读) | d.year → 2023 |
| date.month | 月份(1-12,只读) | d.month → 5 |
| date.day | 日(1-31,只读) | d.day → 15 |
| date.weekday() | 返回星期几(0=周一,6=周日) | d.weekday() → 0 |
| date.isoformat() | 返回 YYYY-MM-DD 格式字符串 | d.isoformat() → "2023-05-15" |
| date.strftime(format) | 自定义格式化输出 | d.strftime("%Y/%m/%d") → "2023/05/15" |
| 方法/属性 | 说明 | 示例 |
|---|---|---|
| time.hour | 小时(0-23,只读) | t.hour → 14 |
| time.minute | 分钟(0-59,只读) | t.minute → 30 |
| time.second | 秒(0-59,只读) | t.second → 0 |
| time.microsecond | 微秒(0-999999,只读) | t.microsecond → 0 |
| time.isoformat() | 返回 HH:MM:SS.mmmmmm 格式字符串 | t.isoformat() → "14:30:00" |
| time.strftime(format) | 自定义格式化输出 | t.strftime("%H:%M") → "14:30" |
| 方法/属性 | 说明 | 示例 |
|---|---|---|
| datetime.now() | 返回当前本地日期时间 | datetime.now() → datetime(2023, 5, 15, 14, 30, 0) |
| datetime.utcnow() | 返回当前 UTC 日期时间 | datetime.utcnow() |
| datetime.fromtimestamp(ts) | 从时间戳创建 datetime 对象 | datetime.fromtimestamp(1684146600) |
| datetime.timestamp() | 返回时间戳(浮点数秒) | dt.timestamp() → 1684146600.0 |
| datetime.date() | 提取日期部分 | dt.date() → date(2023, 5, 15) |
| datetime.time() | 提取时间部分 | dt.time() → time(14, 30) |
| datetime.year | 年份(同 date) | dt.year → 2023 |
| datetime.strftime(format) | 自定义格式化输出 | dt.strftime("%Y-%m-%d %H:%M") → "2023-05-15 14:30" |
| 属性 | 说明 | 示例 |
|---|---|---|
| days | 天数(可正可负) | delta.days → 5 |
| seconds | 秒数(0-86399) | delta.seconds → 3600(1小时) |
| microseconds | 微秒数(0-999999) | delta.microseconds → 0 |
| 符号 | 说明 | 示例输出 |
|---|---|---|
| %Y | 四位年份 | 2023 |
| %m | 两位月份(01-12) | 05 |
| %d | 两位日(01-31) | 15 |
| %H | 24小时制小时(00-23) | 14 |
| %M | 分钟(00-59) | 30 |
| %S | 秒(00-59) | 00 |
| %A | 完整星期名 | Monday |
| %a | 缩写星期名 | Mon |
| %B | 完整月份名 | May |
| %b | 缩写月份名 | May |
日期验证:创建日期时要确保日期有效
时区处理:涉及多时区时要明确时区信息
性能考虑:频繁创建datetime对象可能影响性能
格式化符号:strftime的格式化符号要正确使用
不可变对象:datetime对象不可变,操作会返回新对象
datetime模块提供了完整的日期时间处理功能:
日期时间创建:可以创建任意日期时间对象
格式化显示:支持各种格式的日期时间显示
时间计算:可以计算时间差、未来过去时间
日期比较:支持日期时间的比较操作
时区处理:可以处理不同时区的时间
常用场景:
记录操作时间戳
计算任务执行时间
生成日期报告
处理用户输入的日期
定时任务调度
更多datetime模块的高级用法可以在fly63网站的Python时间处理专题中找到。掌握datetime模块对于处理任何与时间相关的编程任务都非常重要。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!