Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine season given timestamp in Python using 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.

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.

like image 806
Dan Avatar asked Apr 22 '13 04:04

Dan


People also ask

How do I extract a date from a timestamp in Python?

For this, we will use the strptime() method and Pandas module. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function and dt. date from Pandas in Python.

How do I convert a timestamp to a date in Python?

Converting timestamp to datetime We may use the datetime module's fromtimestamp() method to convert the timestamp back to a datetime object. It returns the POSIX timestamp corresponding to the local date and time, as returned by time. time().

What is datetime timestamp Python?

What is timestamp in Python? Timestamp is the date and time of occurrence of an event. In Python we can get the timestamp of an event to an accuracy of milliseconds. The timestamp format in Python returns the time elapsed from the epoch time which is set to 00:00:00 UTC for 1 January 1970.

How can I get date from datetime?

The today() method of date class under DateTime module returns a date object which contains the value of Today's date. Returns: Return the current local date.


1 Answers

It might be easier just to use the day of year parameter. It's not much different than your approach, but possibly easier to understand than the magic numbers.

# 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'
like image 135
jheddings Avatar answered Sep 25 '22 04:09

jheddings