Python datetime,try-except-else-finally

持续更新中

该python学习专栏仅仅用于记录个人在python学习过程中遇到的一些语法和问题,不包括详细的python语法知识。对于python初学者友好。

1、
datetime.date.today() 创建一个 date 对象,仅仅包含了年、月、日。
datetime.datetime.today() 创建一个datatime对象,包含年、月、日、时、分、秒。

import datetime
d1 = datetime.datetime.today()  # d1:2022-08-10 10:55:33.260403
d2 = datetime.date.today()  # d2:2022-08-10

使用 timedelta 函数来对 date 对象进行时间的加减操作
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)其中参数都是可选,默认值为0

import datetime
d0 = datetime.datetime.now()
d1 = datetime.datetime.now()+datetime.timedelta(hours=-2) # 得到两小时以前的时间
d2 = datetime.date.today()+datetime.timedelta(days=-2) # 得到两天以前的时间
# d0:2022-08-10 11:22:42.217313
# d1:2022-08-10 09:20:30.659898
# d2:2022-08-08

使用 strftime 函数根据一个 date 对象来创建具有特定格式的字符串,

import datetime

date1 = datetime.date.today().strftime('%m/%d/%Y')  # 08/10/2022
date2 = datetime.date.today().strftime('%b %d, %Y')  # Aug 10, 2022
date3 = datetime.date.today().strftime('%Y-%m-%d')  # 2022-08-10
date4 = datetime.date.today().strftime('%B %d, %Y')  # August 10, 2022

2、 try-except-else-finally
使用 try-except 代码块来有效地捕获和处理异常的方法

# 完整形式:
try:
    # 可能产生异常的代码块
except [ (Error1, Error2, ... ) [as e] ]:
    # 处理异常的代码块1
except [ (Error3, Error4, ... ) [as e] ]:
    # 处理异常的代码块2
except  [Exception]:
    # 处理其它异常
else:
	# 执行完前面两步后,才执行代码块
finally:
	# 不论是否产生异常,都要执行的代码块

该格式中,[ ] 括起来的部分可以使用,也可以省略。其中各部分的含义如下: (Error1, Error2,…) 、(Error3, Error4,…):其中,Error1、Error2、Error3 和 Error4 都是具体的异常类型,一个 except
块可以同时处理多种异常。
[as e]:作为可选参数,表示给异常类型起一个别名 e,这样做的好处是方便在 except 块中调用异常类型。
[Exception]:作为可选参数,可以代指程序可能发生的所有异常情况,其通常用在最后一个 except 块。

当程序发生不同的意外情况时,会对应特定的异常类型,Python 解释器会根据该异常类型选择对应的 except 块来处理该异常。
例如:

try:
    a = int(input("输入被除数:"))
    b = int(input("输入除数:"))
    c = a / b
    print("您输入的两个数相除的结果是:", c)
except (ValueError, ArithmeticError) as e:
	print(e)
    print("程序发生了数字格式异常、算术异常之一")
except:
    print("未知异常")
else:
    print("程序继续运行")
finally:
    print("程序结束")
    exit(0)
# 输出结果:
# 输入被除数:10 
# 输入除数:0
# division by zero
# 程序发生了数字格式异常、算术异常之一
# 程序结束
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为城w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值