python - 使用日期时间在Python中确定给定时间戳的季节

标签 python date python-2.6

我想使用日期时间模块(而不是时间)从时间戳中仅提取月份和日期,然后根据固定日期确定它是否属于给定季节(秋季、夏季、冬季、 Spring )至日和春分。

例如,如果日期在 3 月 21 日至 6 月 20 日之间,则为 Spring 。与年份无关。我希望它只查看月份和日期,而忽略计算中的年份。

我在使用这个时遇到了麻烦,因为 the month is not being extracted properly from my data , for this reason .

最佳答案

if the date falls between March 21 and June 20, it is spring. Regardless of the year. I want it to just look at the month and day and ignore the year in this calculation.

#!/usr/bin/env python
from datetime import date, datetime

Y = 2000 # dummy leap year to allow input X-02-29 (leap day)
seasons = [('winter', (date(Y,  1,  1),  date(Y,  3, 20))),
           ('spring', (date(Y,  3, 21),  date(Y,  6, 20))),
           ('summer', (date(Y,  6, 21),  date(Y,  9, 22))),
           ('autumn', (date(Y,  9, 23),  date(Y, 12, 20))),
           ('winter', (date(Y, 12, 21),  date(Y, 12, 31)))]

def get_season(now):
    if isinstance(now, datetime):
        now = now.date()
    now = now.replace(year=Y)
    return next(season for season, (start, end) in seasons
                if start <= now <= end)

print(get_season(date.today()))

它是 @Manuel G answer 的扩展版本支持任何一年。

关于python - 使用日期时间在Python中确定给定时间戳的季节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139306/

相关文章:

python - 我怎样才能反转切片?

python - tensorflow 的 tables_initializer 有什么作用?

android - 比较日期值

java - 在java中将字符串转换为日期

python - 在 OS X 10.6.8 上安装 numpy 的问题

python - 如何优化 Python 中大型(75,000 项) bool 值集的操作?

python - pip 列出了错误安装的软件包版本?

python - 如何并排制作两个地 block

python - 从列表字典中创建列表

arrays - 日期字典数组