确定使用Python的datetime赛季定的时间戳(Determine season given

2019-08-31 17:00发布

我想唯一的月份和日期从一个时间戳使用datetime模块(没有时间)基础上,夏至,冬至的固定日期来提取,然后确定它是否属于一个给定的赛季(秋季,夏季,冬季,春季)内分点。

举例来说,如果日期落在3月21日和6月20日之间,它是春天。 无论一年。 我希望它只是看的月份和日期,而忽略了今年这个计算。

我一直在运行陷入困境使用,是因为没有从我的数据正确提取的月份 , 因为这个原因 。

Answer 1:

如果日期落在3月21日和6月20日之间,它是春天。 无论一年。 我希望它只是看的月份和日期,而忽略了今年这个计算。

#!/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摹答案来支持任何一年。



Answer 2:

它可能会更容易只使用一年参数的一天。 这不是比你的做法非常不同,但可能更容易比幻数理解。

# get the current day of the year
doy = datetime.today().timetuple().tm_yday

# "day of year" ranges for the northern hemisphere
spring = range(80, 172)
summer = range(172, 264)
fall = range(264, 355)
# winter = everything else

if doy in spring:
  season = 'spring'
elif doy in summer:
  season = 'summer'
elif doy in fall:
  season = 'fall'
else:
  season = 'winter'


Answer 3:

这就是我终于解决了。 我怀疑这是最好的解决方案,但它的工作原理。 随意提供更好的解决方案。

import datetime

def get_season(date):
    """
    convert date to month and day as integer (md), e.g. 4/21 = 421, 11/17 = 1117, etc.
    """
    m = date.month * 100
    d = date.day
    md = m + d

    if ((md >= 301) and (md <= 531)):
        s = 0  # spring
    elif ((md > 531) and (md < 901)):
        s = 1  # summer
    elif ((md >= 901) and (md <= 1130)):
        s = 2  # fall
    elif ((md > 1130) and (md <= 0229)):
        s = 3  # winter
    else:
        raise IndexError("Invalid date")

    return s

season = get_season(dt.date())


Answer 4:

你是在半球必须加以考虑。 你必须自己使用地理定位确定半球。

def season(self, HEMISPHERE):
    date = self.now()
    md = date.month * 100 + date.day

    if ((md > 320) and (md < 621)):
        s = 0 #spring
    elif ((md > 620) and (md < 923)):
        s = 1 #summer
    elif ((md > 922) and (md < 1223)):
        s = 2 #fall
    else:
        s = 3 #winter

    if not HEMISPHERE == 'north':
        s = (s + 2) % 3
    return s


Answer 5:

我来到这里寻找如何根据日期映射到季节 ,而这个答案我终于解决它通过以下方式:

def season_of_date(date):
    year = str(date.year)
    seasons = {'spring': pd.date_range(start='21/03/'+year, end='20/06/'+year),
               'summer': pd.date_range(start='21/06/'+year, end='22/09/'+year),
               'autumn': pd.date_range(start='23/09/'+year, end='20/12/'+year)}
    if date in seasons['spring']:
        return 'spring'
    if date in seasons['summer']:
        return 'summer'
    if date in seasons['autumn']:
        return 'autumn'
    else:
        return 'winter'

# Assuming df has a date column of type `datetime`
df['season'] = df.date.map(season_of_date)

因此,在原则上适用于任何一年,给定一个datetime



Answer 6:

这就是我通常使用:

seasons = {'Summer':(datetime(2014,6,21), datetime(2014,9,22)),
           'Autumn':(datetime(2014,9,23), datetime(2014,12,20)),
           'Spring':(datetime(2014,3,21), datetime(2014,6,20))}

def get_season(date):
    for season,(season_start, season_end) in seasons.items():
        if date>=season_start and date<= season_end:
            return season
    else:
        return 'Winter'


Answer 7:

我太新的评论,我的编辑被拒绝,所以这里纠正@adsf效应初探代码。

def season(date, hemisphere):
    ''' date is a datetime object
        hemisphere is either 'north' or 'south', dependent on long/lat.
    '''
    md = date.month * 100 + date.day

    if ((md > 320) and (md < 621)):
        s = 0 #spring
    elif ((md > 620) and (md < 923)):
        s = 1 #summer
    elif ((md > 922) and (md < 1223)):
        s = 2 #fall
    else:
        s = 3 #winter

    if hemisphere != 'north':
        if s < 2:
            s += 2 
        else:
            s -= 2

    return s


文章来源: Determine season given timestamp in Python using datetime