2

How can I make the following code compile:

\documentclass{standalone} 
\usepackage{csvsimple}
\usepackage{datetime2}
\usepackage{filecontents}
\begin{filecontents*}{test.csv}
a,b
2019,00:00:00
2019,00:00:01
2020,00:00:02
2018,00:00:03
2018,00:00:04
\end{filecontents*}
\begin{document}
\csvreader[head to column names,tabular=llllll]{test.csv}{}
{\a&\DTMtime{\b}}
\end{document}

Note that it does compile if I replace \b by 00:00:01

2

The problem is that \DTMtime expects its argument to already be expanded. You can see the problem if you say:

\def\test{00:00:00}
\DTMtime{\test}

this already throws an error. You need to expand first \test and then run \DTMtime on it. One way to do this is by saying

\edef\temp{\noexpand\DTMtime{\test}}\temp

The command \edef defines a new macro by recursively expanding the body of the macro. The command \noexpand stops \DTMtime from being expanded, so that \temp gets defined as \DTMtime{00:00:00} which then works as expected.

I like to define this inside of a macro, say called \eval:

\def\eval#1{\edef\temp{#1}\temp}
\eval{\noexpand\DTMtime{\test}}

Another option is to do this using Latex3. Latex3 defines the macro \exp_args:Nx which \edef's the argument of a macro before calling it, so then \exp_args:Nx\DTMtime{\test} will expand \test first and then run \DTMtime on it. You can define a wrapper macro for \DTMtime that always expands its argument first. Here's sample code for that:

\documentclass{standalone} 
\usepackage{expl3}
\usepackage{datetime2}
\ExplSyntaxOn
\cs_new:Npn\DTMtimex { \exp_args:Nx\DTMtime }
\ExplSyntaxOff

\begin{document}
\def\test{00:00:00}
\DTMtimex{\test}
\end{document}

Here's complete code:

\documentclass{standalone} 
\usepackage{csvsimple}
\usepackage{datetime2}
\usepackage{filecontents}
\begin{filecontents*}{test.csv}
a,b
2019,00:00:00
2019,00:00:01
2020,00:00:02
2018,00:00:03
2018,00:00:04
\end{filecontents*}

\def\eval#1{\edef\temp{#1}\temp}
\def\DTMtimex#1{\eval{\noexpand\DTMtime{#1}}}

\begin{document}
\csvreader[head to column names,tabular=llllll]{test.csv}{}
{\a&\DTMtimex{\b}}
\end{document}

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.