一、date日期
1、使用date()函数构造指定日期
2、使用date.today()获取今天日期
# 使用date()函数构造指定日期
date0 = date(year=2024, month=10, day=10)
# 使用date.today()获取今天日期
date1 = date.today()
print(date0, date1)
# 2024-10-10 2024-01-10
3、日期的类型
# 日期的类型
print(type(date1)) # <class 'datetime.date'>
4、输出的方式
⑴、 调用方法输出
# %Y四位年 %y两位年 %m两位月 %d两位日
print(date1.year, date1.month, date1.day, date1.weekday())
# weekday()从0开始
# 2024 1 10 2
⑵、调用strftime.(),使用%输出
- %Y四位年 %y两位年 %m两位月 %d两位日
①
print(date0.strftime("%Y--%m--%d"))
# 2024 1 10 2
②
print(date1.strftime("%y--%m--%d"))
# 24--01--10
二、time时间
1、使用time()函数构造指定时间
time1 = time(hour=10, minute=3, second=18)
# 10:03:18
2、时间的类型
print(type(time1))
<class 'datetime.time'>
3、使用strftime(),输出时间
- %H小时,%M分钟,%S秒
print(time1.strftime("%H:%M:%S"))
# 10:03:18
三、datetime日期时间
1、使用datetime()函数构造指定日期时间
datetime0 = datetime(year=2024, month=1, day=10, hour=12, minute=16, second=34)
2、使用datetime.now()获取当前日期时间
datetime2 = datetime.now()
print(datetime2)
# 2024-01-10 18:57:44.102256
3、使用strftime()输出时间
print(datetime1.strftime("%Y-%m-%d %H:%M:%S"))
# 2024-01-10 18:57:44
四、timedelta时间增量
1、时间增量的表示
- timedelta时间增量:计算时间的周数、天数、秒数……
- 其中的参数都是复数,weeks= , hours= , days= ,seconds =
timedelta0 = timedelta(weeks=2, hours=3, days=1.2, seconds=56)
print(timedelta0)
# 15 days, 7:48:56
2、运用时间增量修改时间
# 在原有的时间基础上,可以用timedelta对时间进行修改
now = datetime.now()
# 加上时间增量,数据类型还是datetime
future = now + timedelta0
print(type(future), future)
print(future.strftime("%Y/%m/%d %H:%M:%S"))
# <class 'datetime.datetime'> 2024-01-26 17:08:31.775694
# 2024/01/26 17:08:31
五、内置time模块
1、time.time()时间戳
- time.time()整数部分是从1970-1-1 0时到现在的秒数
-
# time.time()整数部分是从1970-1-1 0时到现在的秒数 # 也叫做时间戳 print(time.time()) # 1704937398.1666298
2、 time.strftime("%Y/%m/%d %H:%M:%S")格式化时间
# 获取当前时间,并格式化
print(time.strftime("%Y/%m/%d %H:%M:%S"))
# 2024/01/11 09:47:12
3、time.localtime() 获取当地时间
# 获取当地时间,并格式化
print(time.localtime())
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
print(time.strftime("%Y/%m/%d %H:%M:%S", (1999, 9, 9, 9, 9, 9, 0, 0, 0)))
# time.struct_time(tm_year=2024, tm_mon=1, tm_mday=11, tm_hour=9, tm_min=47, tm_sec=12, tm_wday=3, tm_yday=11, tm_isdst=0)
# 2024/01/11 09:47:12
# 1999/09/09 09:09:09
4、time.ctime() 获取星期、月份、几号、时间、年份
# 获取星期、月份、几号、时间、年份
print(time.ctime())
# Thu Jan 11 09:47:12 2024
六、calendar日历
1、 calendar.calendar()年历
# 年历,传入年份的参数
# print(calendar.calendar(2024))
2、calendar.month(, )月历
# 月历,传入年份、月份的参数
# print(calendar.month(2024, 1))
3、calendar.weekday( , , )计算第周几
# 计算第周几,从0开始;传入年份、月份、日期
print(calendar.weekday(2024, 1, 11))
# 3
4、判断是否是闰年
# 是否是闰年
print(calendar.isleap(2024))
# True