datetime模块
1.date日期类
import datetime
arr = datetime.date(2024, 7, 24)
brr = datetime.date(2024, 7, 22)
# date日期类
print(arr)
print(type(arr))
print("year:", arr.year)
print("month:", arr.month)
print("day:", arr.day)
print("weekday:", arr.weekday()) # 周一到周日为0-6
print(arr - brr)
print(type(arr - brr))
print(arr - (arr - brr))
print(type(arr - (arr - brr)))
# date - date = timedelta
# date - timedelta = date
# date间可以进行判断 > < >= <= = !=
运行输出
2024-07-24
<class 'datetime.date'>
year: 2024
month: 7
day: 24
weekday: 2
2 days, 0:00:00
<class 'datetime.timedelta'>
2024-07-22
<class 'datetime.date'>
2.datetime日期类
import datetime
crr = datetime.datetime(2024, 7, 24, 10, 5, 30)
print(crr)
print(type(crr))
print("date:", crr.date())
print("time:", crr.time())
crr_1 = datetime.date(2024, 7, 24)
crr_2 = datetime.time(10,5,30)
crr_3 = datetime.datetime.combine(crr_1, crr_2)
print(crr_3)
print(crr_3 - crr)
运行输出
2024-07-24 10:05:30
<class 'datetime.datetime'>
date: 2024-07-24
time: 10:05:30
2024-07-24 10:05:30
0:00:00
3.timedelta类
就是时间差
用days, seconds, microseconds(微秒)存储时间间隔
传入 weeks/days/hours/minutes/seconds/milliseconds(毫秒)/microseconds
自动转换成上述三个变量
————————————————————————————
date - date = timedelta
date - timedelta = date
import datetime
drr = datetime.datetime(2024,7,24,22,23,30)
delta_1 = datetime.timedelta(days = 100)
# 计算100天后的日期
err_1 = drr + delta_1
print(err_1)
# 计算100天前的日期
err_2 = drr - delta_1
print(err_2)
frr = datetime.datetime(2024, 7, 24, 10, 5, 30)
grr = datetime.datetime(2023, 7, 24, 10, 5, 52)
delta_2 = frr - grr
print(delta_2) # 时间差
print(delta_2.days) # 时间差的天数
print(delta_2.seconds) # 时间差的秒数
print(delta_2.total_seconds()) # 统一转换为秒
输出
2024-11-01 22:23:30
2024-04-15 22:23:30
365 days, 23:59:38
365
86378
31622378.0
4.日期时间字符串转换
a = datetime.date(2024, 7, 24)
print(a.strftime("%Y--%m--%d"))
b = datetime.time(22,42,6)
print(b.strftime("%H::%M::%S"))
ab = datetime.datetime.combine(a,b)
print(ab.strftime("%Y--%m--%d-%H::%M::%S"))
sss = datetime.datetime.strptime("2023--07--24-22::42::06", "%Y--%m--%d-%H::%M::%S")
print("sss:", sss)
输出
2024--07--24
22::42::06
2024--07--24-22::42::06
sss: 2023-07-24 22:42:06
刷题
可以去蓝桥官网题库练习
1.lanqiao611
整个 20 世纪(1901年 1月 1 日至 2000 年12 月 31日之间),一共有多少个星期一?
这道题包秒的
import datetime
arr = datetime.date(1901, 1, 1)
brr = datetime.date(2000, 12, 31)
count = 0
while arr <= brr:
if arr.weekday() == 0:
count += 1
arr += datetime.timedelta(days=1)
print(count)
今天先这样,明天继续