Search code examples
datetimesastimestampcharacter

How to convert character timestamps in SAS to valid datetime values


I've two different character timestamps in SAS and need to convert them to datetime (24H) values.
What is the preferred way to achieve this?

Sample 1

01-12-2023 09:51 AM
24-08-2023 02:38 PM

Desired output:

01-12-2023 09:51:00
24-08-2023 14:38:00

My solution for Example 1 (not sure if this is the best)

PROC FORMAT;
    picture dmyhms
        . = ' ' 
        other = '%0d-%0m-%0Y %0H:%0M:%0S' (datatype=datetime);
RUN;

INPUT(CATX(" ", SUBSTR(event, 1, 10), SUBSTR(event, 12, 8)),anydtdtm.) FORMAT dmyhms. AS event_dt

Sample 2

20240112T000000.000 GMT
20230929T000000.000 GMT

Desired output:

12-01-2024
29-09-2023

My solution for Example 2 (not sure if this is the best)

INPUT(SUBSTR(event, 1, 8), yymmdd8.) FORMAT=ddmmyyd10. as event_d

Any help very much appreciated!


Solution

  • Regarding Sample 1:

    data have;
       c_ts = '01-12-2023 09:51 AM'; output;
       c_ts = '24-08-2023 02:38 PM'; output;
    run;
    
    data want;
       set have;
       n_ts = input(c_ts, anydtdtm.);
       format n_ts datetime20.;
    run;