我需要根据日期来弄清楚会计年度,而我使用datetime的格式方法。dateTime对象,它正在为具有不同值的相同类型对象生成意外结果
以下是我的代码。
from datetime import datetime
dt = datetime.strptime('2019-03-03','%Y-%m-%d')
## Below line is killing my mind as it is resulting 2019-2018
print('{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year)%100))
# This will produce the result 3 2019 19
print(dt.month, dt.year, (dt.year)%100)
dt = datetime.strptime('2019-04-04','%Y-%m-%d')
# But the below line is working fine as it is resulting 2019-20
print('{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year)%100))
# This will produce the result 4 2019 19
print(dt.month, dt.year, (dt.year)%100)
我期望结果
2018-19 if dt = datetime.strptime('2019-03-03','%Y-%m-%d')
2019-20 if dt = datetime.strptime('2019-04-04','%Y-%m-%d')
我无法用代码找出问题。
## Below line is killing my mind as it is resulting 2019-2018
print('{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year)%100))
好吧,让我们分解您的代码:
'{}-{}'.format(dt.year, (dt.year+1)%100 if dt.month > 3 else dt.year-1,(dt.year)%100)
您有2个 {}
s,但3(!(参数:
-
dt.year
, -
(dt.year+1)%100 if dt.month > 3 else dt.year-1
, -
(dt.year)%100
(因为只有2个{}
s(
而被忽略
如您所见,if/else
仅适用于中间参数。
您想要的是在两个参数上使用此if
,因此您要么需要重复IF或使用括号进行分组。但是分组将导致元组,因此您需要用*
解开这些值(我提到了评论中的分组,但忘记了打开包装(。
用2个IFS解决方案:
'{}-{}'.format(dt.year if dt.month > 3 else dt.year-1,
(dt.year+1)%100 if dt.month > 3 else (dt.year)%100)
您可以看到,一个逗号 - 两个参数。将其分为两行,以使其可读性。
使用一个IF和元组解开包装的解决方案:
'{}-{}'.format( *(dt.year, (dt.year+1)%100) if dt.month > 3 else *(dt.year-1,(dt.year)%100) )
为什么要解开包装?因为'{}-{}'.format( ('2018','19') )
获得了一个元组的参数,而不是两个参数。它不知道该怎么办。*
在前面的拆箱或元组中,并作为正常参数提供。 - 在文档中在此处阅读有关它的更多信息。