You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建符合ISO 8601标准的自定义SAS日期时间格式以转换特定字符型日期

解决SAS中特殊ISO 8601日期时间格式的转换与输出问题

Great question! Let’s break this down into two key tasks: converting your character-based datetime string into a proper SAS datetime numeric variable, and then formatting it back to your desired YYYY-MM-DDT00:00:00.000+00:00 format if you need to output it that way.

1. Convert Character String to SAS Datetime Variable

SAS’s ANYDTDTM informat is incredibly flexible and can handle your full ISO 8601 format (including milliseconds and timezone offset) without any hassle. Use the INPUT() function to make the conversion:

data example;
    input date_char $32.;
    * Convert character string to SAS datetime numeric value;
    date_dt = input(date_char, anydtdtm26.);
    datalines;
2020-01-01T00:00:00.000+00:00
2023-10-15T14:30:45.123+08:00
;
run;

The ANYDTDTM26. informat covers the full length of your input string (26 characters) and automatically parses the date, time, milliseconds, and timezone offset into SAS’s standard datetime numeric value (which counts seconds since January 1, 1960, including decimals for milliseconds).

2. Format Datetime Value Back to Your Desired String

Since no built-in SAS format exactly matches YYYY-MM-DDT00:00:00.000+00:00, you have two solid options:

Use PROC FORMAT to build a custom picture format that combines the components you need:

proc format;
    picture dt_iso8601
        low - high = '%Y-%0m-%0dT%0H:%0M:%0S.%03s%Q' (datatype=datetime)
        ;
run;

Let’s break down the format code:

  • %Y-%0m-%0d: Outputs year-month-day, with %0m/%0d ensuring two-digit values (padding with 0 if needed)
  • T%0H:%0M:%0S.%03s: Adds the T separator, then hour:minute:second with three-digit milliseconds
  • %Q: Appends the timezone offset in +HH:MM format

Apply this format in your data step to get the target string:

data output_example;
    set example;
    date_target = put(date_dt, dt_iso8601.);
run;

Option 2: Concatenate Built-in Formats (Quick One-off Use)

If you only need this once, you can directly concatenate outputs from two existing formats:

data output_example;
    set example;
    * Combine datetime-with-milliseconds and timezone components;
    date_target = catx('', put(date_dt, e8601dt23.), put(date_dt, e8601dz5.));
run;

Here, E8601DT23. outputs YYYY-MM-DDT00:00:00.000 and E8601DZ5. outputs +00:00—CATX() sticks them together without extra spaces.

Verify the Result

Either approach will give you the exact format you need: 2020-01-01T00:00:00.000+00:00 for your sample input. Plus, the date_dt variable is a proper SAS datetime value, so you can use it for calculations, filtering, or any other date-time operations.

内容的提问来源于stack exchange,提问作者Kermit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 05:03:12