Hot answers tagged date-and-time
22
Just a literal implementation of a formula for the day of the week:
Clear[dow];
dow[{year_, month_, day_, _ : 0, _ : 0, _ : 0}] :=
Module[{Y = If[month == 1 || month == 2, year - 1, year],
m = Mod[month + 9, 12] + 1, y, c,
s = {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}},
y = Mod[Y, 100];
c = Quotient[Y, 100];
...
21
I will provide one solution which will be using Java and a simple Java reloader I recently introduced. This solution brings to the table up to 100-fold speed-up for large lists of dates.
Preparation
I will borrow @Mike's functions to generate a random list of dates, from his code in his recent question
RandomDateList[] := {
RandomInteger[{1800, 2100}], ...
17
Since I'm living in Europe I'm sticking to the European definition of week number which is equivalent to the ISO standard. According to this standard, a week starts on Monday and the first week is the week containing 4 January. Taking this into account you could do therefore do something like
weekNumberISO[date_] := Module[{day0, year},
With[{days = ...
17
You can use DateDifference to find the time between January 1st and April 17th:
DateDifference["Jan. 1", "April 17", "Week"]
(* {15.2857, "Week"} *)
If you want the "week number" as you've put it, you can just do:
Ceiling@First@DateDifference["Jan. 1", "April 17", "Week"]
which gives 16.
Edit based on Szabolcs's comment: To ensure this works for Jan ...
14
The format specification for DateList is pretty flexible. Since we know that we have <h3> tags wrapped around things, we can just account for them:
DateList[{#, {"<h3>", "MonthName", "Day", ",", "Year", "</h3>"}}] & /@ Flatten[dates]
(*
==> {{2001, 1, 18, 0, 0, 0.}, {2001, 2, 1, 0, 0, 0.}, {2001, 2, 2, 0, 0, 0.},
{2001, 2, ...
12
I've shown off Larsen's method before (and see this as well), but here it is as a formal answer:
larsen[{yr_Integer, mo_Integer, da_Integer, ___}] := Module[{y = yr, m = mo, d = da, q},
If[m < 3, y--; m += 12];
q = d + 2 m + 1 + Quotient[3 (m + 1), 5] + y + Quotient[y, 4] +
Quotient[y, 400] - Quotient[y, 100];
{Sunday, Monday, Tuesday, ...
12
data = FinancialData["SPY", "Jan. 1, 2011"] /. {d_List, v_} :> {AbsoluteTime@d, v};
model = a x^4 + b x^3 + c x^2 + d x + e;
fit = FindFit[data, model, {a, b, c, d, e}, x]
modelf = Function[{x}, Evaluate[model /. fit]]
Plot[modelf[x], {x, Min@data[[All, 1]], Max@data[[All, 1]]}, Epilog -> Map[Point, data]]
Edit
Better (tick labels showing dates)
...
12
Import[(* file *), "Table", "DateStringFormat" -> {"Year", "-", "Month", "-", "Day"}] seems to work...
As a test:
Export["test.dat",
{{"2010-05-19", 17}, {"2010-05-20", 20}, {"2010-05-21", 19}},
"FieldSeparators" -> " "];
Import["test.dat", "Table",
"DateStringFormat" -> {"Year", "-", "Month", "-", "Day"}]
{{{2010, 5, 19}, ...
12
It took me quite a while, but finally, here's a visualization of the perigee of Flamsteed's comet:
I should first note two things: first, some of the needed data for computing the orbit of comet C/1683 O1 was missing in AstronomicalData["CometC1683O1", "Properties"], and I had to pull information from external sources to supplement the information ...
11
Assuming that the days and times in the gathered data list are strings you could do something like
days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday"};
data2 = Reap[
Sow[(AbsoluteTime[#2] - AbsoluteTime["00:00:00"])/3600., #1] & @@@
Flatten[data, 1],
days, #2 &][[2, All, 1]];
...
11
Using Simon's data:
In[6]:= datelist = {"29/02/2008", "15/12/2007", "06/09/2007",
"06/10/2008", "05/03/2007", "24/01/2010", "19/06/2009",
"03/11/2009", "02/02/2010", "25/12/2009"};
We can just sort the data by the absolute time:
In[7]:= SortBy[datelist, AbsoluteTime[{#, {"Day", "Month", "Year"}}] &]
Out[7]= {"05/03/2007", "06/09/2007", ...
10
This recent post reminded me that AbsoluteTime is a fast kernel function.
Using the RandomDates function from Leonid's post:
dates = RandomDates[500000];
Needs["Calendar`"]
rls = Thread[
Range[0, 6] ->
{Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday}
];
Timing[result1 = DayOfWeek /@ dates;]
Timing[result2 = ...
10
To fit a function and to calculate the moving average you need to convert your dates in absolute time using AbsoluteTime[].
data = FinancialData["IBM", "Jan. 1, 2004"];
newdata =
Table[{AbsoluteTime[data[[i, 1]]], data[[i, 2]]}, {i, Length[data]}];
lm = LinearModelFit[newdata, x, x];
movAvg = MovingAverage[newdata, 200];
...
10
So this generates the heatmap:
<< Calendar`
year = 1990;
yearLen = DaysBetween[{year, 1, 1}, {year, 12, 31}] + 1;
data = RandomReal[1, yearLen];
days = Map[DayOfWeek[{year, 1, #}] &, Range[3, 9]];
day1 = Position[days, DayOfWeek[{year, 1, 1}]][[1, 1]];
dayn = Position[days, DayOfWeek[{year, 12, 1}]][[1, 1]];
Paddata = Join[ConstantArray[100, day1 ...
10
A simple string-based approach is to swap the order of day/month/year, do the Sort and then swap back again:
(* Example data *)
datelist = DateString[# + AbsoluteTime[{2007, 01, 01}],
{"Day", "/", "Month", "/", "Year"}] & /@ RandomInteger[10^8, 10]
{"29/02/2008", "15/12/2007", "06/09/2007", "06/10/2008",
"05/03/2007", "24/01/2010", ...
9
Jean Meeus's Astronomical Algorithms (as well as the related book Astronomical Formulæ for Calculators) is what you should start looking at whenever you need to deal with algorithms for quantities of astronomical interest.
For instance, here is a translation of Meeus's method for the Julian Date:
Options[jd] = {"Calendar" -> "Gregorian"};
...
9
You can get about 100 times faster by using Java, without any particular tuning, but you will have to provide the date format explicitly. Here is the solution based on Java reloader.
Implementation
Load the Java reloader
Compile the following class:
JCompileLoad@
"
import java.text.ParseException;
import java.text.SimpleDateFormat;
import ...
8
Ok, Java solution, by popular demand.
Solution
Load the Java reloader
Compile this class:
JCompileLoad@
"import java.util.Calendar;
public class SecondOfYearVectorized{
public static double[] secondOfYear(int[][] dates){
Calendar calendar = Calendar.getInstance();
double[] result = new double[dates.length];
for(int ...
8
Options will do it:
data = {{{2006, 10, 1}, 10}, {{2006, 10, 15}, 12},
{{2006, 10, 30}, 15}, {{2006, 11, 20}, 20}};
plot = DateListPlot[data];
Options[plot, FrameTicks]
For example, modifying the contents of FrameTicks:
data = {DateList[{2006, #, 1}], #} & /@ Range[40];
plot = DateListPlot[data];
ticks = FrameTicks /. Options[plot, FrameTicks];
...
8
Without reading Leonid's answer (which is probably better) I recommend something like this:
fillDates[dates_] :=
Module[{f, all},
all = Part[DateList /@ (Range[##, 24*60^2] & @@
AbsoluteTime /@ dates[[{1, -1}, 1]]), All, {1, 2, 3}];
(f[#[[1]]] = #) & ~Scan~ dates;
f[x_] := {x, 0};
f /@ all
]
fillDates @ {{{2012, 1, 1}, 1}, {{2012, ...
8
I'll start with a slightly reformatted version of your data:
data = {{"Monday", 3}, {"Tuesday", 4}, {"Wednesday", 6}, {"Thursday", 6}, {"Friday", 10},
{"Saturday", 12}, {"Sunday", 11}, {"Monday", 3}, {"Tuesday", 4}, {"Wednesday", 4},
{"Thursday", 5}, {"Friday", 10}, {"Saturday", 10}, {"Sunday", 9}, {"Monday", 2},
{"Tuesday", 3}, ...
8
I confess to being allergic to database operations that require data to be in a particular sort order: it's too easy for huge mistakes to creep in. What is needed here is to turn the source list (say, list1) into a lookup table so it reliably returns its value (second element in the list) when given its key (first element in the list).
To assure ...
7
I believe that SplitBy works. Using very simple data:
data = {
{{2012,1,1,0,0,0},1},{{2012,1,1,0,0,1},2},{{2012,1,1,0,1,0},3},
{{2012,1,2,0,0,0},4},{{2012,1,2,0,0,1},5},
{{2012,1,3,0,0,0},6}
};
divided = SplitBy[data,#[[1,1;;3]]&];
Column[divided,Dividers -> All]
Note that SplitBy[data,f] splits between x1 and x2 when f[x1]=!=f[x2]. In the ...
7
You can use Gather which will do all the work for you:
Gather[data, #1[[1, 1 ;; 3]] == #2[[1, 1 ;; 3]] &]
{{{{2012, 1, 1, 0, 0, 0}, 1}, {{2012, 1, 1, 0, 0, 1},
2}, {{2012, 1, 1, 0, 1, 0}, 3}}, {{{2012, 1, 2, 0, 0, 0},
4}, {{2012, 1, 2, 0, 0, 1}, 5}}, {{{2012, 1, 3, 0, 0, 0}, 6}}}
For an alternative way of generating a range of dates, ...
7
This is not a full answer, but more a response to J.M.'s comment and provides a routine to calculate $\Delta T$ which was sitting on my hard disk. This is intended as a starting point for further calculations.
deltaT::usage =
"deltaT[date] calculate the arithmetic difference, in seconds, \
between the Terrestrial Dynamical Time (TD) and the Universal \
...
6
Needs["JLink`"];
AddToClassPath[ToFileName[{$HomeDirectory,"javafiles","joda-time-2.1"}]];
JavaNew["org.joda.time.DateTime",2012,4,17,0,0]@dayOfWeek[]@getAsText[]
Super-fast. You need the Joda Time library for that.
If you're a hardcore JLink user, you have the first two lines in your init.m anyway, so the problem reduces to 71 characters, with an amazing ...
6
Since your data already has dates in the form {Y, M, D} you could do without DateList, and as mentioned by J. M. you can use Last in place of Last[#] &, therefore you could use:
Last /@ SplitBy[data, #[[2]] &]
Since as the operation above shows you are only looking at the second column, you might use a numeric operation and Pick:
Pick[data, ...
6
Search for brfASTRO.m which is a fantastic astronomy package that Peter Breitfeld wrote. He offers wonderful material on his homepage. I used many of his routines (thank you Peter!)
Here is my (long but untested) version which I probably also copied partly and forgot from where. Please contact me if you feel that proper credit is due!
This is a small part ...
6
You should really consider changing your data format! In Mathematica, you have several ways to express a time or date.
In the following, I use your values for Monday, Tuesday, ... in a list to transform the first part of every pair, so that we have a valid date. For this I use Round[10*2.1] which ends in 21; then, taking the IntegerDigits from it lets me ...
6
Date is deprecated. According to the Mathematica 5 documentation, Date[z] returns the time in time zone z.
You probably want to use DateList to accomplish the kinds of things you are describing. The following will add an hour and a half to the current date:
date = DateList[]
DatePlus[date, 3/48]
(* Out:
{2012, 11, 15, 12, 7, 3.572165}
{2012, 11, 15, ...
Only top voted, non community-wiki answers of a minimum length are eligible


