Python中常用的日期和时间函数介绍及使用技巧
在Python编程中,日期和时间是非常常见的操作。Python内置了丰富的日期和时间函数,可以方便地进行日期和时间的计算、转化、显示等处理。下面介绍一些常用的日期和时间函数及使用技巧。
1. datetime模块
datetime是Python内置的日期和时间模块,它包含了date、time、datetime等类。其中,date类表示日期,time类表示时间,datetime类表示日期和时间。
(1) 获取当前日期和时间
使用datetime模块的now()函数可以获取当前日期和时间。示例代码如下:
import datetime now = datetime.datetime.now() print(now)
输出样例:
2021-08-12 13:57:26.542593
(2) 获取指定日期和时间
可以使用date、time、datetime类的构造函数来获取指定的日期和时间。示例代码如下:
import datetime d = datetime.date(2021,8,12) t = datetime.time(14,28,30) dt = datetime.datetime(2021,8,12,14,28,30) print(d) print(t) print(dt)
输出样例:
2021-08-12 14:28:30 2021-08-12 14:28:30
(3) 日期和时间的加减运算
可以使用datetime模块的timedelta类来进行日期和时间的加减运算。示例代码如下:
import datetime d1 = datetime.date(2021,8,12) d2 = d1 + datetime.timedelta(days=7) print(d1) print(d2) t1 = datetime.time(14,28,30) t2 = datetime.datetime.now().time() print(t1) print(t2) dt1 = datetime.datetime(2021,8,12,14,28,30) dt2 = dt1 + datetime.timedelta(hours=2) print(dt1) print(dt2)
输出样例:
2021-08-12 2021-08-19 14:28:30 15:04:12.184214 2021-08-12 14:28:30 2021-08-12 16:28:30
2. time模块
time模块是Python内置的时间模块,它主要提供了与时间有关的函数。
(1) 获取时间戳
使用time模块的time()函数可以获取当前时间戳,即从1970年1月1日午夜到现在的秒数。示例代码如下:
import time timestamp = time.time() print(timestamp)
输出样例:
1628774928.2908833
(2) 时间的格式化显示
使用time模块的strftime()函数可以将时间格式化为字符串。示例代码如下:
import time
timestamp = time.time()
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print(time_str)
输出样例:
2021-08-12 14:19:11
(3) 时间的延时处理
使用time模块的sleep()函数可以对程序进行延时处理。示例代码如下:
import time
print("start...")
time.sleep(2)
print("end...")
输出样例:
start... end...
在输出“start...”后,程序被休眠2秒后再输出“end...”。
3. calendar模块
calendar模块是Python内置的日历模块,它主要提供了与日历相关的函数。
(1) 显示当前月份的日历
使用calendar模块的month()函数可以显示当前月份的日历。示例代码如下:
import calendar year = datetime.datetime.now().year month = datetime.datetime.now().month print(calendar.month(year, month))
输出样例:
August 2021
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
(2) 判断是否为闰年
使用calendar模块的isleap()函数可以判断指定的年份是否为闰年。示例代码如下:
import calendar
year = datetime.datetime.now().year
if calendar.isleap(year):
print("%d is a leap year." % year)
else:
print("%d is not a leap year." % year)
输出样例:
2021 is not a leap year.
以上介绍了Python中常用的日期和时间函数及使用技巧,供大家参考。
