Python中的时间模块有哪些功能
发布时间:2023-12-13 21:23:50
Python中的时间模块是指time、datetime、calendar这三个模块,它们分别提供了不同的时间处理功能。下面分别介绍它们的功能并给出使用例子。
1. time 模块
time 模块提供了处理时间的基本功能,包括获取当前时间、时间戳转换、睡眠等。
- 获取当前时间
import time current_time = time.localtime() print(current_time) # 输出:time.struct_time(tm_year=2022, tm_mon=11, tm_mday=17, tm_hour=22, tm_min=48, tm_sec=37, tm_wday=3, tm_yday=321, tm_isdst=0)
- 时间戳转换
import time timestamp = time.time() print(timestamp) # 输出:1637173363.758578
- 睡眠
import time
print("start")
time.sleep(3)
print("end")
# 输出:
# start
# (等待3秒)
# end
2. datetime 模块
datetime 模块提供了处理日期和时间的功能,包括创建日期对象、日期格式化等。
- 创建日期对象
import datetime # 获取当前日期和时间 current_datetime = datetime.datetime.now() print(current_datetime) # 创建指定日期和时间的对象 specific_datetime = datetime.datetime(2022, 11, 17, 22, 50, 0) print(specific_datetime)
- 日期格式化
import datetime
current_datetime = datetime.datetime.now()
# 格式化为字符串
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime)
# 字符串转为日期对象
str_datetime = "2022-11-17 22:50:00"
datetime_obj = datetime.datetime.strptime(str_datetime, "%Y-%m-%d %H:%M:%S")
print(datetime_obj)
3. calendar 模块
calendar 模块提供了处理日历的功能,包括生成月份日历、判断闰年等。
- 生成月份日历
import calendar # 生成当前月份的日历 current_calendar = calendar.monthcalendar(2022, 11) print(current_calendar) # 输出: # [[0, 0, 0, 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, 0, 0]]
- 判断闰年
import calendar # 判断是否为闰年 is_leap = calendar.isleap(2022) print(is_leap) # 输出:False
除了以上功能之外,这些模块还提供了其他更多的功能,如时间格式化、时间增减、时区转换等。通过使用这些模块,我们可以方便地处理各种时间相关的操作。需要根据具体的需求选择合适的模块和方法来完成相应的任务。
