datetime模块练习

我的未来我决定 提交于 2019-12-06 16:31:47
#_author:来童星#date:2019/12/6#1.获取当前日期import datetimeprint(datetime.date.today())# 2019-12-06#2.使用today和now获取当前日期和时间,时间精确到毫秒级print(datetime.datetime.today())# 2019-12-06 11:23:11.102894print(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 Fridayprint(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 Decemberprint(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.006867print(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.418294print(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.384559print(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.683086print(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-08print(minute.strftime('%Y-%m-%d  %H:%M'))# 2019-12-08  14:18print(minute.strftime('%Y-%m-%d  %H:%M:%S'))# 2019-12-08  14:18:23
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!