Python 时间函数的使用方法
发布时间:2023-06-15 11:15:43
Python 时间函数的使用方法
Python 的 datetime 模块提供了许多用于处理日期时间的函数,我们可以使用这些函数来获取当前时间、格式化时间、计算时间间隔等。
下面是 Python 中常用的时间函数:
1. 获取当前时间:
import datetime
now = datetime.datetime.now()
print("当前时间为:",now)
输出结果如下:
当前时间为:2022-03-24 16:30:02.211884
2. 获取当前日期:
import datetime
today = datetime.date.today()
print("当前日期为:",today)
输出结果如下:
当前日期为: 2022-03-24
3. 格式化时间:
import datetime
now = datetime.datetime.now()
# 格式化为字符串
time_str = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的时间为:",time_str)
# 格式化为时间元组
time_tuple = now.timetuple()
print("格式化后的时间元组为:",time_tuple)
# 格式化为时间戳
time_stamp = now.timestamp()
print("格式化后的时间戳为:",time_stamp)
输出结果如下:
格式化后的时间为:2022-03-24 17:06:41 格式化后的时间元组为:time.struct_time(tm_year=2022, tm_mon=3, tm_mday=24, tm_hour=17, tm_min=6, tm_sec=41, tm_wday=3, tm_yday=83, tm_isdst=-1) 格式化后的时间戳为:1648724801.056938
4. 时间计算:
import datetime
now = datetime.datetime.now()
# 加上 1 天
next_day = now + datetime.timedelta(days=1)
print("加上 1 天的时间为:",next_day)
# 减去 2 小时
last_hour = now - datetime.timedelta(hours=2)
print("减去 2 小时的时间为:",last_hour)
# 计算两个时间之间的时间差
time_diff = next_day - last_hour
print("两个时间之间的时间差为:",time_diff)
输出结果如下:
加上 1 天的时间为:2022-03-25 17:58:25.306798 减去 2 小时的时间为:2022-03-24 15:58:25.306798 两个时间之间的时间差为:0:02:00:00.000000
5. 其他常用函数:
import datetime
now = datetime.datetime.now()
# 获取年份
year = now.year
print("当前时间的年份为:",year)
# 获取月份
month = now.month
print("当前时间的月份为:",month)
# 获取日期
day = now.day
print("当前时间的日期为:",day)
# 获取小时
hour = now.hour
print("当前时间的小时为:",hour)
# 获取分钟
minute = now.minute
print("当前时间的分钟为:",minute)
# 获取秒数
second = now.second
print("当前时间的秒数为:",second)
输出结果如下:
当前时间的年份为: 2022 当前时间的月份为: 3 当前时间的日期为: 24 当前时间的小时为: 18 当前时间的分钟为: 30 当前时间的秒数为: 58
总结
Python 中的时间函数非常强大,我们可以使用它们来完成各种时间相关的操作。在实际开发中,我们可以根据需求选择相应的时间函数来处理时间。了解 Python 时间函数的使用方法可以帮助我们更加高效地开发程序。
