我想使用 datetime 模块(不是时间)仅从时间戳中提取月份和日期,然后根据至日的固定日期确定它是否属于给定季节(秋季、夏季、冬季、春季)和春分。
例如,如果日期介于 3 月 21 日和 6 月 20 日之间,则为春天。不分年份。我希望它只查看月份和日期而忽略此计算中的年份。
我想使用 datetime 模块(不是时间)仅从时间戳中提取月份和日期,然后根据至日的固定日期确定它是否属于给定季节(秋季、夏季、冬季、春季)和春分。
例如,如果日期介于 3 月 21 日和 6 月 20 日之间,则为春天。不分年份。我希望它只查看月份和日期而忽略此计算中的年份。
如果日期介于 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 G 答案的扩展版本,可支持任何年份。
仅使用年份参数可能更容易。它与您的方法没有太大不同,但可能比魔术数字更容易理解。
# 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'
我来到这里寻找如何将日期映射到季节,并基于这个答案,我最终通过以下方式解决了它:
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
.
必须考虑您所在的半球。您必须自己使用地理定位来确定半球。
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
我对评论太新了,我的编辑被拒绝了,所以这里是@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
我想你可以用pandas.Series.dt.quarter
吗?例如,
datetime = pd.Series(pd.to_datetime(['2010-09-30', '2010-04-25', '2010-01-25', '2010-10-29', '2010-12-25']))
seasons = datetime.dt.quarter
seasons:
0 3
1 2
2 1
3 4
4 4
季节会是你想要的吗?
这就是我最终解决它的方法。我怀疑这是最好的解决方案,但它确实有效。随时提供更好的解决方案。
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())
这是我通常使用的:
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'
使用 python 日期时间和简单的字典
import datetime
date = datetime.datetime.strptime('01/05/2015 01:30:00 PM', "%m/%d/%Y %H:%M:%S %p")
//using above created date for the code below
seasons = {1:[12,1,2],2:[3,4,5],3:[6,7,8],4:[9,10,11]}
ss={}
for k,v in seasons.items():
for e in v:
ss[e] = k
print(ss[date.month])