返回
Python Datetime:39个小例子来拯救因时间而抓狂的你
后端
2024-02-01 17:37:45
嗨,大家好,欢迎来到我的技术博客。今天,我们将踏上一个时间探索之旅,深入 Python 的 Datetime 库。无论你是编程新手还是经验丰富的开发人员,掌握时间处理的诀窍都是至关重要的。
在软件开发中,时间无处不在。从记录事件的时间戳到处理用户输入的日期,Datetime 库为我们提供了丰富的工具,让我们轻松驾驭时间这个维度。为了让大家迅速上手,我准备了 39 个精挑细选的示例,涵盖了 Datetime 库的方方面面。
1. 创建日期和时间对象
import datetime
# 创建当前日期和时间
now = datetime.datetime.now()
# 创建指定日期和时间
specific_date = datetime.datetime(2023, 3, 8, 14, 30)
2. 获取日期和时间组件
# 获取日期部分
date_part = now.date()
# 获取时间部分
time_part = now.time()
# 获取年、月、日、时、分、秒
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
3. 比较日期和时间
# 比较两个日期
date1 = datetime.date(2023, 3, 8)
date2 = datetime.date(2023, 3, 9)
result = date1 < date2
# 比较两个时间
time1 = datetime.time(14, 30)
time2 = datetime.time(15, 00)
result = time1 < time2
4. 执行时间算术
# 增加天数
new_date = now + datetime.timedelta(days=10)
# 减少小时
new_time = now - datetime.timedelta(hours=2)
# 计算两个日期之间的天数差
days_diff = date2 - date1
5. 格式化日期和时间
# 将日期格式化为字符串
date_str = date1.strftime("%Y-%m-%d")
# 将时间格式化为字符串
time_str = time1.strftime("%H:%M:%S")
# 自定义格式化字符串
custom_format = "%A, %B %d, %Y"
formatted_date = now.strftime(custom_format)
6. 转换时区
# 创建时区对象
timezone = datetime.timezone(datetime.timedelta(hours=5))
# 将时间转换为指定时区
converted_time = now.astimezone(timezone)
7. 解析日期和时间字符串
# 从字符串解析日期
date_from_str = datetime.datetime.strptime("2023-03-08", "%Y-%m-%d")
# 从字符串解析时间
time_from_str = datetime.datetime.strptime("14:30", "%H:%M")
8. 处理闰年
# 检查是否是闰年
is_leap_year = datetime.date(2024, 2, 29).year % 4 == 0
9. 获取当前时间戳
# 获取当前时间戳
timestamp = datetime.datetime.now().timestamp()
10. 创建定时器
import time
# 创建定时器
timer = time.time()
# 运行耗时代码
# 计算耗时
elapsed_time = time.time() - timer
11. 使用相对时间
# 创建相对时间对象
relative_time = datetime.timedelta(days=10, hours=5)
# 添加相对时间到当前时间
new_time = now + relative_time
12. 处理时区转换
# 将时间从 UTC 转换为本地时区
local_time = now.astimezone()
# 将时间从本地时区转换为 UTC
utc_time = now.astimezone(datetime.timezone.utc)
13. 使用日历模块
import calendar
# 获取指定月份的日历
month_calendar = calendar.monthcalendar(2023, 3)
14. 使用 Dateutil 库
from dateutil import parser, relativedelta
# 使用 Dateutil 解析日期和时间字符串
parsed_datetime = parser.parse("2023-03-08 14:30")
# 使用 Dateutil 创建相对时间对象
relative_delta = relativedelta.relativedelta(years=1)
15. 使用 arrow 库
import arrow
# 使用 Arrow 创建日期和时间对象
arrow_datetime = arrow.now()
# 使用 Arrow 执行时间算术
new_arrow_datetime = arrow_datetime.shift(days=10)
16. 处理 JSON 中的日期和时间
import json
# 将日期和时间对象转换为 JSON 字符串
json_datetime = json.dumps(now)
# 将 JSON 字符串转换为日期和时间对象
new_datetime = json.loads(json_datetime)
17. 使用 Pandas 处理时间序列数据
import pandas as pd
# 创建时间序列数据框
df = pd.DataFrame({'date': ['2023-03-01', '2023-03-02', '2023-03-03'], 'value': [10, 20, 30]})
# 提取时间戳
df['timestamp'] = pd.to_datetime(df['date'])
18. 使用 SQLAlchemy 处理数据库中的日期和时间
import sqlalchemy as sa
# 创建 SQLAlchemy 模型
class MyModel(sa.Model):
__tablename__ = 'my_table'
id = sa.Column(sa.Integer, primary_key=True)
created_at = sa.Column(sa.DateTime, default=sa.func.now())
19. 其他有用的 Datetime 库
总结
掌握 Python 的 Datetime 库对于任何希望高效处理时间和日期的开发者来说至关重要。通过本文提供的 39 个示例,你已经装备了处理各种时间相关任务的知识和技巧。希望这些示例能让你在时间维度上纵横驰骋,并拯救你因时间而抓狂的时刻。