第六篇 Python中日期时间相关(快来学习!!!)

 datetime 模块下包含date、time、datetime、timedelta

1.date:构造日期

# date.today()直接获取今天的日期
# date(year= , month= , day= ,)构造指定的日期
# strftime 将时间格式化格式化

date0 = date(year=2001, month=1, day=10)
# 获取今天日期
date0 = date.today()
print(type(date0))
#  取得日期中每一个部分
print(date0.year, date0.month, date0.day, date0.weekday())

2.time: 构造时间

time0 = time(hour=17, minute=1, second=30)
print(type(time0))
print(time0.hour, time0.minute, time0.second)
print(time0.strftime("%H:%M:%S"))

 # %H表示小时     %M表示分钟      %S表示秒

print(time.localtime())
print(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime()))
# 获取本地时间的年、月、日、时、分、秒

3 datetime:构造时间日期

datetime0 = datetime(year=2001, month=5, day=25, hour=5, minute=29, second=11)
datetime0 = datetime.now()
print(type(datetime0))
print(datetime0.year, datetime0.month, datetime0.day, datetime0.hour, datetime0.minute, datetime0.second)
print(datetime0.strftime("%Y-%m-%d %H:%M:%S"))

# %Y是表示4位年   %y表示两位年     %m表示两位月     %d表示两位日 

4 timedelta:时间增量

now = datetime.now()
print(now.strftime("%Y/%m/%d %H:%M:%S"))
timedelta0 = timedelta(weeks=1, days=1, hours=2, seconds=30)
print(timedelta0.days, timedelta0.seconds)
future = now + timedelta(weeks=2, hours=2)
print(type(future), future.strftime("%Y/%m/%d %H:%M:%S"))
future = now - timedelta(hours=8)
print(type(future), future.strftime("%Y/%m/%d %H:%M:%S"))

# future的时间日期是在现在的时间日期基础上加上时间增量

5.time:时间模块

# time sleep(几秒) 阻塞模块、等待秒数
# time.time 整数部分是从1970-1-1 0时到现在的秒数 以秒为单位的时间戳
# time.strftime("%Y/%m/%d %H:%M:%S",(1999,9,9,9,9,9,0,0,0))

import time
print(time)
print(1)
time.sleep(5)
print(2)
time.sleep(5)
print(3)
time.sleep(5)

 # 打印数字1、2、3,间隔5秒再打印下一个数

print(time.time())
time.sleep(5)
print(time.time())
time.sleep(5)
print(time.time())

 # time.time整数部分是从1970-1-1 0时到现在的秒数

6. calendar:日历

import calendar
print(calendar)
# 年历
print(calendar.calendar(2024))
# 月历
print(calendar.month(2024, 1))
# 周几
print(calendar.weekday(2024, 1, 11))
# 是否为闰年
print(calendar.isleap(2001))

# 这里的weekday是打印周几,这里的周几是0-6,从0开始 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值