datetime模块练习

#_author:来童星
#date:2019/12/6
#1.获取当前日期
import datetime
print(datetime.date.today())# 2019-12-06
#2.使用today和now获取当前日期和时间,时间精确到毫秒级
print(datetime.datetime.today())# 2019-12-06 11:23:11.102894
print(datetime.datetime.now())#2019-12-06 11:23:11.102893
#3.使用strftime()格式化时间为标准格式
#strftime可以将日期输出为我们想要的格式(要特别注意参数区分大小写),如:只输出日期
print(datetime.datetime.now().strftime('%Y-%m-%d'))# 2019-12-06
#如果输出当前日期和时间,精确到秒,设置日期时间参数即可
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))# 2019-12-06
#如果输出当前日期和时间,星期,%A是星期全写的参数,%a是星期简写的参数
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %A '))# 2019-12-06 11:33:11 Friday
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %a '))# 2019-12-06 11:33:11 Fri
#如果输出当前日期和时间,星期,月份,%B是月份全写的参数,%b是月份简写的参数
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %A %B '))# 2019-12-06 11:33:11 Friday December
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %a %b '))# 2019-12-06 11:33:11 Fri Dec
#4.倒计时计算
#使用strptime对象实现倒计时,首先要设置一个未来的时间,通过strptime对象设置未来时间,设置的时间包括年月日小时分秒
#如:计算到2020年元旦还有多少天
future=datetime.datetime.strptime('2020-1-1 0:0:0','%Y-%m-%d %H:%M:%S')
#用未来的时间和现在的时间做差计算出天数,小时,分秒,下面计算天数
now=datetime.datetime.today()
day_sub=future-now#day_sub存储两个时间的时间,差精确到秒
day=day_sub.days#获取两个时间之间的天数
#接下来算小时,分和秒
hour=int(day_sub.seconds/60/60)# 使用int函数把小时取整
minute=int((day_sub.seconds-hour*60*60)/60)# 使用int函数把分钟取整
second=day_sub.seconds-hour*60*60-minute*60# 使用int函数把秒取整
#然后输出到2020年元旦还有多长时
print('到2020年元旦还有'+str(day)+'天'+str(minute)+'分'+str(second)+'秒')# 到2020年元旦还有25天57分35秒
#5.计算未来或过去的时间
#如果想计算从现在到未来多少天后是几号,或已经过去的多少天是几号,可以使用datetime模块的timedelta对象结合具体事件对象来实现
#example:实现 5天后是几号
print(datetime.datetime.now())# 2019-12-06 12:08:23.006867
print(datetime.datetime.now()+datetime.timedelta(days=5))# 2019-12-11 12:08:23.006867
# 实现 5天前是几号
print(datetime.datetime.now())# 2019-12-06 12:09:59.418294
print(datetime.datetime.now()-datetime.timedelta(days=5))#2019-12-01 12:09:59.418294
#计算300小时后是几号
print(datetime.datetime.now())# 2019-12-06 12:11:57.384559
print(datetime.datetime.now()+datetime.timedelta(hours=300))# 2019-12-19 00:11:57.384559
#计算3000分钟是几号
print(datetime.datetime.now())# 2019-12-06 12:13:47.683086
print(datetime.datetime.now()+datetime.timedelta(minutes=3000))# 2019-12-08 14:13:47.683086
#6.精确到日期,分钟和秒
minute=datetime.datetime.now()+datetime.timedelta(minutes=3000)
print(minute.strftime('%Y-%m-%d'))# 2019-12-08
print(minute.strftime('%Y-%m-%d %H:%M'))# 2019-12-08 14:18
print(minute.strftime('%Y-%m-%d %H:%M:%S'))# 2019-12-08 14:18:23




原文地址:https://www.cnblogs.com/startl/p/11994562.html