用Python计算日期 [英] Count Dates in Python
本文介绍了用Python计算日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用Python(从1950年到2050年)计算每年13号星期五的数目(我知道,有点晚了)。我不熟悉要使用的任何日期/日历包。有什么想法吗?
I am trying to count the number of Friday the 13ths per year from 1950-2050 using Python (I know, a little late). I am not familiar with any date/calendar packages to use. Any thoughts?
推荐答案
这是直接解决方案。使用 sum 来计算每月的13号是星期五的次数:
This has a direct solution. Use sum to count the number of times where the 13th of the month is a Friday:
>>> from datetime import datetime # the function datetime from module datetime
>>> sum(datetime(year, month, 13).weekday() == 4
for year in range(1950, 2051) for month in range(1,13))
174
这篇关于用Python计算日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文