Message Boards Message Boards

GROUPS:

Converting a list of dates

Posted 1 year ago
3136 Views
|
5 Replies
|
3 Total Likes
|

How do I covert a list of dates with format {{3/8/2020}, {3/9/2020},{3/10/2020},.......} to a list with format {{2020,3,8},{2020,3,9},{2020,3,10},......}?

5 Replies
Posted 1 year ago

Use DateList and extract the year-month-date:

(DateList /@ {"3/8/2020", "3/9/2020"})[[All, {1, 2, 3}]]
(* {{2020,3,8},{2020,3,9}} *)

EDIT: Sorry -- I didn't notice the inner brackets. Still supposing the date is a string:

(DateList[#[[1]]] & /@ {{"3/8/2020"}, {"3/9/2020"}})[[All, {1, 2, 3}]]

(* {{2020,3,8},{2020,3,9}} *)

EDIT 2:

Switch off Warning::ambig to suppress warning messages, then switch back on if you like:

Off[DateList::ambig]

newList = (DateList[#[[1]]] & /@ {{"3/8/2020"}, {"3/9/2020"}})[[All, \
{1, 2, 3}]]

(* {{2020,3,8},{2020,3,9}} *)

On[DateList::ambig]
Posted 1 year ago

If your input is in this form then

swap[l_List]:=Map[{#[[3]],#[[1]],#[[2]]}&,l];
fixdate[l_List]:=swap[Map[ToExpression[StringReplace["{"<>#<>"}","/"->","]]&,l]];
fixdate[{{"3/8/2020"},{"3/9/2020"},{"3/10/2020"}}]

returns

{{2020,3,8},{2020,3,9},{2020,3,10}}

Thank you Bill and David. Both methods work fine. But with David's method there is a the problem that for day numbers smaller than 13 an ambiguity warning is shown. That makes the method less useful for a CDF. Or is there maybe a code for preventing such a warning? Bill's method taught me that I still have a lot to learn about pure functions!

Posted 1 year ago

Hi Laurens, you can turn off the warming message. I updated my answer to demonstrate. You could also suppress all messages with Quiet[], but that would suppress other error messages as well.

Here is one more approach - purely on basis of strings:

(* operator for conversion: *)
conv = StringRiffle[RotateRight[StringSplit[#, "/"]], "/"] &;
(* test data *)
dl = {{"3/8/2020"}, {"3/9/2020"}, {"3/10/2020"}, {"3/13/2020"}, {"3/15/2020"}};
Map[conv, dl, {2}]
(*  Out: {{"2020/3/8"},{"2020/3/9"},{"2020/3/10"},{"2020/3/13"},{"2020/3/15"}}  *)
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract