在Python中将年/月/日转换为年 [英] Convert Year/Month/Day to Day of Year in Python
问题描述
我使用Pythondatetime模块,即:
I'm using the Python "datetime" module, i.e.:
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
我想计算闰年敏感的年份。例如oday(2009年3月6日)是2009年第65天。这里是基于Web的DateTime计算器。
and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. Here's web-based DateTime calculator.
无论如何,我看到两个选项:
Anyway, I see a two options:
-
创建一个number_of_days_in_month array = [31,28,...],决定是否是闰年,手动总结日期
Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days
使用datetime.timedelta猜测然后二进制搜索一年中的正确日期:
Use datetime.timedelta to make a guess & then binary search for the correct day of year:
。
>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
这些都觉得很笨重我有一种直觉,有一种更计数的计算方式是一年中的一年。任何想法/建议?
These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?
推荐答案
有一个非常简单的解决方案:
There is a very simple solution:
day_of_year = datetime.now().timetuple().tm_yday
这篇关于在Python中将年/月/日转换为年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!