日期与时间
datetime模块基础
datetime模块提供了处理日期和时间的主要类。
from datetime import datetime, date, time
# 获取当前时间
now = datetime.now()
print(f"当前时间: {now}")
# 输出: 当前时间: 2024-01-15 14:30:00.123456
# 创建特定日期时间
specific_date = datetime(2024, 12, 25, 10, 30, 0)
print(f"圣诞节: {specific_date}")
# 输出: 圣诞节: 2024-12-25 10:30:00
# 从字符串解析
date_string = "2024-01-15 14:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"解析后: {parsed_date}")
格式化日期时间
使用strftime()方法将日期时间格式化为字符串。
from datetime import datetime
now = datetime.now()
# 常用格式
print(now.strftime("%Y-%m-%d")) # 输出: 2024-01-15
print(now.strftime("%Y/%m/%d")) # 输出: 2024/01/15
print(now.strftime("%H:%M:%S")) # 输出: 14:30:00
print(now.strftime("%Y年%m月%d日 %H:%M:%S")) # 输出: 2024年01月15日 14:30:00
# 常用格式符号
# %Y - 四位年份
# %m - 月份(01-12)
# %d - 日期(01-31)
# %H - 小时(00-23)
# %M - 分钟(00-59)
# %S - 秒(00-59)
# %A - 星期全名
# %a - 星期缩写
# %B - 月份全名
# %b - 月份缩写
日期时间运算
from datetime import datetime, timedelta
now = datetime.now()
# 时间差
future = now + timedelta(days=7)
past = now - timedelta(days=7)
print(f"一周后: {future}")
print(f"一周前: {past}")
# 计算两个日期之间的差
date1 = datetime(2024, 1, 1)
date2 = datetime(2024, 12, 31)
diff = date2 - date1
print(f"天数差: {diff.days}") # 输出: 天数差: 365
# 时间差的运算
delta = timedelta(hours=2, minutes=30)
new_time = now + delta
print(f"2小时30分后: {new_time}")
date和time类
from datetime import date, time
# date类
today = date.today()
print(f"今天: {today}")
print(f"年: {today.year}")
print(f"月: {today.month}")
print(f"日: {today.day}")
print(f"星期: {today.weekday()}") # 0=周一,6=周日
# time类
current_time = time(14, 30, 0)
print(f"时间: {current_time}")
print(f"小时: {current_time.hour}")
print(f"分钟: {current_time.minute}")
print(f"秒: {current_time.second}")
time模块
time模块提供了更底层的时间处理功能。
import time
# 获取时间戳
timestamp = time.time()
print(f"时间戳: {timestamp}") # 输出: 时间戳: 1705312200.123456
# 时间戳转换为结构化时间
struct_time = time.localtime(timestamp)
print(f"结构化时间: {struct_time}")
# 格式化输出
formatted = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(f"格式化时间: {formatted}")
# 暂停执行
print("开始")
time.sleep(2) # 暂停2秒
print("结束")
calendar模块
calendar模块提供了日历相关的功能。
import calendar
# 打印月历
print(calendar.month(2024, 1))
# 输出:
# January 2024
# Mo Tu We Th Fr Sa Su
# 1 2 3 4 5 6 7
# 8 9 10 11 12 13 14
# 15 16 17 18 19 20 21
# 22 23 24 25 26 27 28
# 29 30 31
# 打印年历
print(calendar.calendar(2024))
# 判断闰年
print(calendar.isleap(2024)) # 输出: True
print(calendar.isleap(2023)) # 输出: False
# 获取某月的天数
days = calendar.monthrange(2024, 2)
print(f"2024年2月有{days[1]}天") # 输出: 2024年2月有29天
时区处理
from datetime import datetime, timezone, timedelta
# UTC时间
utc_now = datetime.now(timezone.utc)
print(f"UTC时间: {utc_now}")
# 创建时区
UTC = timezone.utc
CST = timezone(timedelta(hours=8)) # 中国标准时间
# 转换时区
utc_time = datetime.now(UTC)
cst_time = utc_time.astimezone(CST)
print(f"UTC: {utc_time}")
print(f"CST: {cst_time}")
# 使用pytz处理时区(推荐)
# import pytz
#
# # 获取时区
# beijing_tz = pytz.timezone('Asia/Shanghai')
# tokyo_tz = pytz.timezone('Asia/Tokyo')
#
# # 转换时区
# beijing_time = utc_time.astimezone(beijing_tz)
# tokyo_time = utc_time.astimezone(tokyo_tz)
实际应用案例
1. 计算年龄
from datetime import date
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
# 使用
birthday = date(1990, 5, 15)
age = calculate_age(birthday)
print(f"年龄: {age}")
2. 日期范围生成
from datetime import date, timedelta
def date_range(start_date, end_date):
"""生成日期范围"""
current = start_date
while current <= end_date:
yield current
current += timedelta(days=1)
# 使用
start = date(2024, 1, 1)
end = date(2024, 1, 10)
for d in date_range(start, end):
print(d.strftime("%Y-%m-%d"))
3. 工作日计算
from datetime import date, timedelta
def is_workday(d):
"""判断是否为工作日"""
return d.weekday() < 5 # 周一到周五
def add_workdays(start_date, days):
"""增加工作日"""
current = start_date
added_days = 0
while added_days < days:
current += timedelta(days=1)
if is_workday(current):
added_days += 1
return current
# 使用
start = date(2024, 1, 15) # 周一
end_date = add_workdays(start, 10) # 增加10个工作日
print(f"10个工作日后: {end_date}")
4. 时间戳转换
from datetime import datetime
def timestamp_to_datetime(timestamp):
"""时间戳转日期时间"""
return datetime.fromtimestamp(timestamp)
def datetime_to_timestamp(dt):
"""日期时间转时间戳"""
return dt.timestamp()
# 使用
now = datetime.now()
ts = datetime_to_timestamp(now)
print(f"时间戳: {ts}")
dt = timestamp_to_datetime(ts)
print(f"日期时间: {dt}")
最佳实践
- 优先使用
datetime模块而非time模块 - 处理时区时考虑使用
pytz或zoneinfo - 存储时间时使用UTC,显示时转换为本地时区
- 使用
timedelta进行日期时间运算 - 注意闰年和夏令时的影响
正确处理日期时间对于编写可靠的应用程序至关重要。