Python 上个月有 2 位数
Python previous month with 2 digit
我想要 04 作为 premonth 的输出。有人可以帮忙吗?试过 diff 格式,但没有成功。
enter code here
premonth = str(int(time.strftime('%m'))-1)
尝试使用
python date of the previous month
但由于 strftime 限制,我无法继续。
这不是最好的方法,但应该可行:
a = str(int(time.strftime('%m'))-1)
a = '0'+a if len(a)==1 else a
以下 f 字符串将为您提供所需的内容,它还通过使用算术运算正确处理一月,以确保 1
变为 12
:
f'{(int(time.strftime("%m")) + 10) % 12 + 1:02}'
分解一下,f-string 是一种从任意表达式构建字符串的现代方法,以一种将格式和数据保持在一起的方式(不同于旧的 "string".format(item, item)
甚至 旧的 "string" % (item, item)
).
f 字符串内部是一个看起来相当复杂的表达式,其格式为 :02
,表示两个位置,左侧用零填充。
表达式是通过适当换行正确减少您的月份的原因,正如您从以下 table 中看到的那样:
+-------+-----+-----+----++-------+-----+-----+----+
| Value | +10 | %12 | +1 || Value | +10 | %12 | +1 |
+-------+-----+-----+----++-------+-----+-----+----+
| 1 | 11 | 11 | 12 || 7 | 17 | 5 | 6 |
| 2 | 12 | 0 | 1 || 8 | 18 | 6 | 7 |
| 3 | 13 | 1 | 2 || 9 | 19 | 7 | 8 |
| 4 | 14 | 2 | 3 || 10 | 20 | 8 | 9 |
| 5 | 15 | 3 | 4 || 11 | 21 | 9 | 10 |
| 6 | 16 | 4 | 5 || 12 | 22 | 10 | 11 |
+-------+-----+-----+----++-------+-----+-----+----+
和以下语句:
print(", ".join([f'{mm}->{(mm + 10) % 12 + 1:02}' for mm in range(1, 13)]))
输出:
1->12, 2->01, 3->02, 4->03, 5->04, 6->05, 7->06, 8->07, 9->08, 10->09, 11->10, 12->11
我想要 04 作为 premonth 的输出。有人可以帮忙吗?试过 diff 格式,但没有成功。
enter code here
premonth = str(int(time.strftime('%m'))-1)
尝试使用 python date of the previous month 但由于 strftime 限制,我无法继续。
这不是最好的方法,但应该可行:
a = str(int(time.strftime('%m'))-1)
a = '0'+a if len(a)==1 else a
以下 f 字符串将为您提供所需的内容,它还通过使用算术运算正确处理一月,以确保 1
变为 12
:
f'{(int(time.strftime("%m")) + 10) % 12 + 1:02}'
分解一下,f-string 是一种从任意表达式构建字符串的现代方法,以一种将格式和数据保持在一起的方式(不同于旧的 "string".format(item, item)
甚至 旧的 "string" % (item, item)
).
f 字符串内部是一个看起来相当复杂的表达式,其格式为 :02
,表示两个位置,左侧用零填充。
表达式是通过适当换行正确减少您的月份的原因,正如您从以下 table 中看到的那样:
+-------+-----+-----+----++-------+-----+-----+----+
| Value | +10 | %12 | +1 || Value | +10 | %12 | +1 |
+-------+-----+-----+----++-------+-----+-----+----+
| 1 | 11 | 11 | 12 || 7 | 17 | 5 | 6 |
| 2 | 12 | 0 | 1 || 8 | 18 | 6 | 7 |
| 3 | 13 | 1 | 2 || 9 | 19 | 7 | 8 |
| 4 | 14 | 2 | 3 || 10 | 20 | 8 | 9 |
| 5 | 15 | 3 | 4 || 11 | 21 | 9 | 10 |
| 6 | 16 | 4 | 5 || 12 | 22 | 10 | 11 |
+-------+-----+-----+----++-------+-----+-----+----+
和以下语句:
print(", ".join([f'{mm}->{(mm + 10) % 12 + 1:02}' for mm in range(1, 13)]))
输出:
1->12, 2->01, 3->02, 4->03, 5->04, 6->05, 7->06, 8->07, 9->08, 10->09, 11->10, 12->11