2
$\begingroup$

I have a list imported from a CSV:

a = {{2018-07-0308-PM},{2018-07-0307-PM},{2018-07-0306-PM},{2018-07-0305-PM}}

and want to convert these into a DateObject[].

DateObject[#,{"Year","Month","Day","Hour", "AMPM"}] & /@ Map[ToString, a]

Which only gives:

{DateObject[{2018-07-0308-PM},{Year,Month,Day,Hour,AMPM}],DateObject[{2018-07-0307-PM},{Year,Month,Day,Hour,AMPM}]}

Any idea how to do this?

$\endgroup$
1
  • 1
    $\begingroup$ If a is the result of importing the list from the CSV file, what is the Head of each element of a? If it is a list of strings, then try Map[First, a] instead of Map[ToString, a]. $\endgroup$ Jul 5, 2018 at 20:58

1 Answer 1

1
$\begingroup$
a = {{"2018-07-0308-PM"}, {"2018-07-0307-PM"}, {"2018-07-0306-PM"}, {"2018-07-0305-PM"}}

DateObject[
 DateString[{First@#, {"Year", "-", "Month", "-", "Day", "Hour", "-", "AMPM"}}]
] & /@ a

(* {DateObject[{2018, 7, 3, 20, 0, 0.}, "Instant", "Gregorian", -5.], 
    DateObject[{2018, 7, 3, 19, 0, 0.}, "Instant", "Gregorian", -5.], 
    DateObject[{2018, 7, 3, 18, 0, 0.}, "Instant", "Gregorian", -5.], 
    DateObject[{2018, 7, 3, 17, 0, 0.}, "Instant", "Gregorian", -5.]} *)
$\endgroup$
3
  • $\begingroup$ Thanks. Why is it not possible to use a nested Map[...] syntax? Which I like a bit more as it's more explicit. $\endgroup$ Jul 6, 2018 at 9:32
  • $\begingroup$ You can use Nested Map like: Map[DateObject[ DateString[{#, {"Year", "-", "Month", "-", "Day", "Hour", "-", "AMPM"}}]] &, a, {2}] $\endgroup$
    – dsingh
    Jul 6, 2018 at 13:54
  • $\begingroup$ I was missing the & operator to make it a pure function. Thanks. $\endgroup$ Jul 10, 2018 at 13:51

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.