如何使用 Pendulum 在 Python 中计算一年中的天数
我们可以使用优秀的 pendulum 库来查找给定年份的天数
days_in_year_pendulum.py
import pendulum
def number_of_days_in_year(year):
start = pendulum.date(year, 1, 1)
end = start.add(years=1)
return (end - start).in_days()使用示例:
usage_pendulum.py
print(number_of_days_in_year(2020)) # Prints 366
print(number_of_days_in_year(2021)) # Prints 365说明:
首先,我们定义 start 日期为我们感兴趣的年份的第一天(1月1日):
example_pendulum_snippet.py
start = pendulum.date(year, 1, 1)现在我们使用 pendulum 的 add 函数向该日期添加正好一年。这将始终得到给定年份下一年的1月1日:
end_date_example.py
end = start.add(years=1)其余很简单:只需让 pendulum 给我们 end 和 start 之间差值的天数:
days_diff_example.py
(end - start).in_days()Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow