我想使用日期时间模块(而不是时间)从时间戳中提取月份和日期,然后根据至日的固定日期确定它是否属于给定季节(秋季,夏季,冬季,春季)分点.
例如,如果日期在3月21日到6月20日之间,那就是春天.无论一年如何.我希望它只是查看月份和日期,并忽略此计算中的年份.
我一直在运行陷入困境使用,是因为没有从我的数据正确提取的月份,因为这个原因.
使用day of year参数可能更容易.它与你的方法没什么不同,但可能比神奇的数字更容易理解.
# 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'
Run Code Online (Sandbox Code Playgroud)
如果日期在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()))
Run Code Online (Sandbox Code Playgroud)
它是@Manuel G的扩展版本,支持任何一年的支持.
我来到这里是为了寻找如何将日期映射到季节,基于这个答案,我最终通过以下方式解决了这个问题:
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)
Run Code Online (Sandbox Code Playgroud)
所以原则上它适用于任何一年,给定一个datetime.
| 归档时间: |
|
| 查看次数: |
11987 次 |
| 最近记录: |