Message Boards Message Boards

0
|
6911 Views
|
5 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Converting a list of dates

Posted 4 years ago

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},......}?

POSTED BY: Laurens Wachters
5 Replies
Posted 4 years 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 BY: David Keith
Posted 4 years 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}}
POSTED BY: Bill Nelson

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 BY: Laurens Wachters

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"}}  *)
POSTED BY: Henrik Schachner
Posted 4 years 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.

POSTED BY: David Keith
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