在Python中使用datetime来确定给定的时间戳 [英] Determine season given timestamp in Python using datetime

查看:282
本文介绍了在Python中使用datetime来确定给定的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想使用datetime模块(而不是时间)从时间戳中提取月份和日期,然后根据固定的日期确定是否在给定的季节(秋季,夏季,冬季,春季)零星和平分。

I'd like to extract only the month and day from a timestamp using the datetime module (not time) and then determine if it falls within a given season (fall, summer, winter, spring) based on the fixed dates of the solstices and equinoxes.

例如,如果日期在3月21日到6月20日之间,那是春天。无论一年。我想要看这个月份和日子,忽略这个计算的一年。

For instance, 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.

我一直遇到麻烦,因为该月份没有从我的数据正确提取因此

I've been running into trouble using this because the month is not being extracted properly from my data, for this reason.

推荐答案


如果日期在3月21日到6月20日之间,那是春天。
无论一年。我想要查看月份和日子
,忽略这个计算年份。

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 支持任何一年。

It is an extended version of @Manuel G answer to support any year.

这篇关于在Python中使用datetime来确定给定的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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