在 Python 中将年/月/日转换为一年中的某一天 [英] Convert Year/Month/Day to Day of Year in Python

查看:31
本文介绍了在 Python 中将年/月/日转换为一年中的某一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 datetime 模块,即:

<预><代码>>>>导入日期时间>>>今天 = datetime.datetime.now()>>>打印(今天)2009-03-06 13:24:58.857946

并且我想计算将闰年考虑在内的一年中的哪一天.例如今天(2009 年 3 月 6 日)是 2009 年的第 65 天.

我看到两个选项:

  1. 创建一个 number_of_days_in_month = [31, 28, ...] 数组,判断它是否是闰年并手动求和天数.

  2. 使用 datetime.timedelta 进行猜测 &然后二分查找一年中的正确日期:

    <预><代码>>>>导入日期时间>>>年 = 2009>>>DAY_OF_YEAR = 62>>>d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)

这些都感觉很笨重&我有一种直觉,有一个更Pythonic"的一年中第几天的计算方法.有什么想法/建议吗?

解决方案

使用 datetime.timetuple() 将您的 datetime 对象转换为 time.struct_time 对象然后获取它的 tm_yday 属性:

from datetime import datetimeday_of_year = datetime.now().timetuple().tm_yday # 1 月 1 日返回 1

I'm using the datetime module, i.e.:

>>> import datetime
>>> today = datetime.datetime.now()
>>> print(today)
2009-03-06 13:24:58.857946

and I would like to compute the day of year that takes leap years into account. e.g. today (March 6, 2009) is the 65th day of 2009.

I see a two options:

  1. Create a number_of_days_in_month = [31, 28, ...] array, decide if it's a leap year and manually sum up the days.

  2. Use datetime.timedelta to make a guess & then binary search for the correct day of the 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 the day of the year. Any ideas/suggestions?

解决方案

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st

这篇关于在 Python 中将年/月/日转换为一年中的某一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆