Find Which Season a Particular Date Belongs To

Find which season a particular date belongs to

How about using something like this:

getSeason <- function(DATES) {
WS <- as.Date("2012-12-15", format = "%Y-%m-%d") # Winter Solstice
SE <- as.Date("2012-3-15", format = "%Y-%m-%d") # Spring Equinox
SS <- as.Date("2012-6-15", format = "%Y-%m-%d") # Summer Solstice
FE <- as.Date("2012-9-15", format = "%Y-%m-%d") # Fall Equinox

# Convert dates from any year to 2012 dates
d <- as.Date(strftime(DATES, format="2012-%m-%d"))

ifelse (d >= WS | d < SE, "Winter",
ifelse (d >= SE & d < SS, "Spring",
ifelse (d >= SS & d < FE, "Summer", "Fall")))
}

my.dates <- as.Date("2011-12-01", format = "%Y-%m-%d") + 0:60
head(getSeason(my.dates), 24)
# [1] "Fall" "Fall" "Fall" "Fall" "Fall" "Fall" "Fall"
# [8] "Fall" "Fall" "Fall" "Fall" "Fall" "Fall" "Fall"
# [15] "Winter" "Winter" "Winter" "Winter" "Winter" "Winter"

One note: 2012 is a good year to which to convert all of the dates; since it is a leap year, any February 29ths in your data set will be handled smoothly.

Determine season given timestamp in Python using datetime

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()))

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

Javascript coding: Input a specific date, Output the season

Note, there are saner ways of doing this (for instance, using a date object for instance), that would probably be more useful/flexible, especially if you want to determine by the actual season start/stop date (March 28th, for example). This is just to demonstrate a starting point.

Here's a very simple example, using a swtich() to return a season according to a numeric month:

http://jsfiddle.net/RtC58/

<form name="date">
<input type="text" name="month"/>
<input type="button" value="Season?" onClick="getSeason()"/>
</form>

function getSeason() {
month = document.forms.date.month.value;
season = '';
switch(month) {
case '12':
case '1':
case '2':
season = 'winter';
break;
case '3':
case '4':
case '5':
season = 'spring';
break;
case '6':
case '7':
case '8':
season = 'summer';
break;
case '9':
case '10':
case '11':
season = 'fall';
break;
}
alert(season);
}

Here's a little bit more complex example, showing the short/long month plus the numeric month.

http://jsfiddle.net/RtC58/1/

function getSeason() {
month = document.forms.date.month.value.toLowerCase();
season = 'unknown';
switch(month) {
case 'dec':
case 'december':
case '12':
case 'jan':
case 'january':
case '1':
case 'feb':
case 'february':
case '2':
season = 'winter';
break;
case 'mar':
case 'march':
case '3':
case 'apr':
case 'april':
case '4':
case 'may':
case '5':
season = 'spring';
break;
case 'jun':
case 'june':
case '6':
case 'jul':
case 'july':
case '7':
case 'aug':
case 'august':
case '8':
season = 'summer';
break;
case 'sep':
case 'september':
case '9':
case 'oct':
case 'october':
case '10':
case 'nov':
case 'november':
case '11':
season = 'fall';
break;
}
alert(season);
}

A little bit different approach could be to create variables for the seasons, use if/else statements (as the OP wants an example of) and find the 'index of' the month value in the one of the variables (note I added a , [comma] to the end of the month to disambiguate 1 from 12 and 1 from 0, etc...).

http://jsfiddle.net/RtC58/3/

function getSeason() {
month = document.forms.date.month.value.toLowerCase()+",";
winter = 'dec,december,jan,january,feb,february,12,1,2,';
spring = 'mar,march,apr,april,may,3,4,5,';
summer = 'jun,june,jul,july,aug,august,6,7,8,';
fall = 'sep,september,oct,october,nov,november,9,10,11,';
season = 'unknown';
if (winter.indexOf(month) != -1) {
season = 'winter';
} else if (spring.indexOf(month) != -1) {
season = 'spring';
} else if (summer.indexOf(month) != -1) {
season = 'summer';
} else if (fall.indexOf(month) != -1) {
season = 'fall';
}
alert(season);
}

WHERE Clause to find all records in a specific month

I think the function you're looking for is MONTH(date). You'll probably want to use 'YEAR' too.

Let's assume you have a table named things that looks something like this:

id happend_at
-- ----------------
1 2009-01-01 12:08
2 2009-02-01 12:00
3 2009-01-12 09:40
4 2009-01-29 17:55

And let's say you want to execute to find all the records that have a happened_at during the month 2009/01 (January 2009). The SQL query would be:

SELECT id FROM things 
WHERE MONTH(happened_at) = 1 AND YEAR(happened_at) = 2009

Which would return:

id
---
1
3
4

Find the date range between the given year and month

You can just check if the start of the current month belongs to the range:

select *
from stf
where date_trunc('month', current_date) between d1 and d2

How to filter a dataframe of dates by a particular month/day?

Map an anonymous function to calculate the month on to the series and compare it to 11 for nov.
That will give you a boolean mask. You can then use that mask to filter your dataframe.

nov_mask = df['Dates'].map(lambda x: x.month) == 11
df[nov_mask]

I don't think there is straight forward way to filter the way you want ignoring the year so try this.

nov_mar_series = pd.Series(pd.date_range("2013-11-15", "2014-03-15"))
#create timestamp without year
nov_mar_no_year = nov_mar_series.map(lambda x: x.strftime("%m-%d"))
#add a yearless timestamp to the dataframe
df["no_year"] = df['Date'].map(lambda x: x.strftime("%m-%d"))
no_year_mask = df['no_year'].isin(nov_mar_no_year)
df[no_year_mask]

Is there a function to determine which quarter of the year a date is in?

Given an instance x of datetime.date, (x.month-1)//3 will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).


Originally two answers, multiply upvoted and even originally accepted (both currently deleted), were buggy -- not doing the -1 before the division, and dividing by 4 instead of 3. Since .month goes 1 to 12, it's easy to check for yourself what formula is right:

for m in range(1, 13):
print m//4 + 1,
print

gives 1 1 1 2 2 2 2 3 3 3 3 4 -- two four-month quarters and a single-month one (eep).

for m in range(1, 13):
print (m-1)//3 + 1,
print

gives 1 1 1 2 2 2 3 3 3 4 4 4 -- now doesn't this look vastly preferable to you?-)

This proves that the question is well warranted, I think;-).

I don't think the datetime module should necessarily have every possible useful calendric function, but I do know I maintain a (well-tested;-) datetools module for the use of my (and others') projects at work, which has many little functions to perform all of these calendric computations -- some are complex, some simple, but there's no reason to do the work over and over (even simple work) or risk bugs in such computations;-).

Find whether a particular date is an Option Expiration Friday - problem with timeDate package

I am guessing it's a timezone problem. What happens if you use this:

format(dates[isOpExFriday], tz="UTC")

On second look, you probably need to put the 'tz=' argument inside the format call inside the as.Date(format(...)) call. The format function "freezes" that dates value as text.

EDIT: On testing however I think you are right about it being a bug. (And I sent a bug report to the maintainer with this response.) Even after trying to insert various timezone specs and setting myFinCenter in RmetricsOptions, I still get the which stems from this error deep inside your choice of functions:

timeNthNdayInMonth(as.Date("2011-09-01"), nday=5, nth=3)
America/New_York
[1] [2011-09-15]

I suspect it is because of this code since as I understand it Julian dates are not adjusted for timezones or daylight savings times:

ct = 24 * 3600 * (as.integer(julian.POSIXt(lt)) + 
(nth - 1) * 7 + (nday - lt1$wday)%%7)
class(ct) = "POSIXct"

The ct value in seconds is then coverted to POSIXct from second since "origin" simply by coercion of class. If I change the code to:

ct=as.POSIXct(ct, origin="1970-01-01")  # correct results come back

My quantmod and timeDate versions are both current per CRAN. Running Mac with R 2.13.1 in 64 bit mode with a US locale. I have not yet tried to reproduce with a minimal session so there could still be some collision or hijacking with other packages:

> sessionInfo()
R version 2.13.1 RC (2011-07-03 r56263)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] grid splines stats graphics grDevices utils datasets
[8] methods base

other attached packages:
[1] quantmod_0.3-17 TTR_0.20-3 xts_0.8-2
[4] Defaults_1.1-1 timeDate_2130.93 zoo_1.7-4
[7] gplots_2.10.1 KernSmooth_2.23-6 caTools_1.12
[10] bitops_1.0-4.1 gdata_2.8.1 gtools_2.6.2
[13] wordnet_0.1-8 ggplot2_0.8.9 proto_0.3-9.2
[16] reshape_0.8.4 plyr_1.6 rattle_2.6.10
[19] RGtk2_2.20.17 rms_3.3-1 Hmisc_3.8-3
[22] survival_2.36-9 sos_1.3-0 brew_1.0-6
[25] lattice_0.19-30


Related Topics



Leave a reply



Submit