1
$\begingroup$

I have a list of datetime objects and numbers, say

enter image description here

When I export to a txt file, it gives

{DateObject[{2017, 1, 1, 0, 0}, "Minute", "Gregorian", 0., {"ISODateTime"}], 0}

{DateObject[{2017, 1, 1, 0, 1}, "Minute", "Gregorian", 0., {"ISODateTime"}], 1}

{DateObject[{2017, 1, 1, 0, 2}, "Minute", "Gregorian", 0., {"ISODateTime"}], 0}

{DateObject[{2017, 1, 1, 0, 3}, "Minute", "Gregorian", 0., {"ISODateTime"}], 0}

Is there any easy way to import the txt file and get back the datetime object?

Many thanks in advance.

$\endgroup$
1
$\begingroup$

It is probably easier to save as a .csv but you can do it with a .txt as follows:

 dateObject = {DateObject[{2017, 1, 1, 0, 0}, "Minute", 
   "Gregorian", 0., {"ISODateTime"}], 
  DateObject[{2017, 1, 1, 0, 1}, "Minute", "Gregorian", 
   0., {"ISODateTime"}], 
  DateObject[{2017, 1, 1, 0, 2}, "Minute", "Gregorian", 
   0., {"ISODateTime"}], 
  DateObject[{2017, 1, 1, 0, 3}, "Minute", "Gregorian", 
   0., {"ISODateTime"}]}

 Export["C:\\Users\\Sarahs\\Desktop\\FileOutput.txt", dateObject];
 input = Import["C:\\Users\\Sarahs\\Desktop\\FileOutput.txt"];

At this point, input is a string with "\n" marking the new lines, so you need to split it up.

split = StringSplit[input, "\n"]

Now you have a bunch of strings so you just need to convert them to an expression.

ToExpression /@ split
$\endgroup$

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.