Python时间函数的操作方法及示例
Python中的时间函数主要包括time、datetime、calendar三个模块。time模块主要用于操作时间戳(时间的浮点数表示),并提供一些函数转换时间格式;datetime模块主要用于操作日期时间,包括获取当前日期、时间、时区等;calendar模块主要用于操作日期时间的日历信息。
在Python中,可以使用各种时间函数来获取或处理时间信息,下面将分别介绍它们的具体用法及示例。
1. time模块:
1.1 time.time()
获取当前时间戳(距离1970年1月1日零点的秒数)。
示例代码:
import time t = time.time() print(t) #输出当前时间戳
1.2 time.localtime()
将时间戳转换为struct_time格式的时间对象,分别表示年、月、日、小时、分钟、秒、星期几、一年中的第几天等信息。
示例代码:
import time t = time.time() time_obj = time.localtime(t) #将时间戳转换为时间对象 print(time_obj) #输出struct_time对象
1.3 time.strftime()
将时间对象转换为指定格式的字符串。
示例代码:
import time
t = time.time()
time_obj = time.localtime(t)
t_str = time.strftime("%Y-%m-%d %H:%M:%S", time_obj) #将时间对象转换为字符串
print(t_str) #输出格式化后的时间字符串
1.4 time.sleep()
延迟一定时间,单位为秒。
示例代码:
import time
print("start")
time.sleep(2) #延迟2秒
print("end")
2. datetime模块:
2.1 datetime.datetime.now()
获取当前时间,返回datetime.datetime格式的对象,包含年、月、日、小时、分钟、秒、微秒等信息。
示例代码:
import datetime now = datetime.datetime.now() print(now) #输出当前时间
2.2 datetime.date.today()
获取当前日期,返回datetime.date格式的对象,包含年、月、日等信息。
示例代码:
import datetime today = datetime.date.today() print(today) #输出当前日期
2.3 datetime.datetime.strftime()
将datetime.datetime格式的时间对象转换为指定格式的字符串。
示例代码:
import datetime
now = datetime.datetime.now()
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
print(now_str) #输出格式化后的时间字符串
2.4 datetime.timedelta()
两个时间之间的差值,可以表示为年、月、日、小时、分钟、秒等粒度。
示例代码:
import datetime now = datetime.datetime.now() future = now + datetime.timedelta(days=10) #计算10天后的时间 duration = future - now #计算两个时间之间的差值 print(duration.days) #输出差值天数
3. calendar模块:
3.1 calendar.calendar()
打印指定年份的日历信息。
示例代码:
import calendar cal = calendar.calendar(2021) print(cal) #输出2021年的日历信息
3.2 calendar.month()
打印指定月份的日历信息。
示例代码:
import calendar cal = calendar.month(2021, 1) print(cal) #输出2021年1月的日历信息
3.3 calendar.weekday()
获取指定日期是星期几,返回0-6的整数,0表示星期一。
示例代码:
import calendar weekday = calendar.weekday(2021, 1, 1) print(weekday) #输出2021年1月1日的星期几,星期五为4
以上是Python中常用的时间函数操作方法及示例,有了这些函数,我们可以方便地处理各种时间信息,让程序更加精确,更加智能化。
