I can convert any DateObject to its current quarter as follows:


But if I want to look at whether my datetime stamp is in the first half or the second half of the year, what is the key for that?

  • 1
    $\begingroup$ The documentation of DateObject lists the granularities available. There does not seem to be a built-in intermediate step between "Year" and "Quarter". $\endgroup$ – MarcoB Dec 18 '19 at 16:44
  • $\begingroup$ Is there a mechanism to create your own granularity? $\endgroup$ – user13892 Dec 18 '19 at 16:55
  • $\begingroup$ How are you intending to use these "YearHalf" DateObjects? $\endgroup$ – Edmund Dec 19 '19 at 0:03
  • $\begingroup$ @Edmund I have one of the date fields acting inside a GroupBy. So I needed different granularity to produce different summary statistics. The keyword "YearHalf" was just my guess (I am not using it). But now since there is no way to have such granularity I have to resort to converting DateObjects to Strings to achieve what I want which is very inefficient since I have very a large dataset. I do think mathematica should provide a way to create custom granularity to keep the code nice and clean. $\endgroup$ – user13892 Dec 19 '19 at 15:11

Since you only need the "YearHalf" concept for grouping you may introduce a DayRound granularity using a yearHalf symbol with TagSetDelayed.

yearHalf /:
 DayRound[d_, yearHalf] :=
   DateValue[d, "Year"],
   6 UnitStep[DateValue[d, "Month"] - 7] + 1,

yearHalf now works with DayRound to make it return 1 January for the first half of the year and 1 July for the second half of the year.

DayRound[#, yearHalf] & /@ DateObject /@ {{2019, 2, 1}, {2019, 9, 30}}

Mathematica graphics

With a few dates.

dates = DateRange[DateObject@{2019, 1, 1}, DateObject@{2020, 6, 1}, "Month"];

Then DayRound can be used in GroupBy to collect the dates by yearHalf.

GroupBy[DayRound[#, yearHalf] &]@dates

Mathematica graphics

Hope this helps.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.