Tuesday, July 17, 2012

Date and Datetime Stamps in SAS, Perl, C#, and VB.NET

When repeating periodic tasks (hourly, daily, monthly, or whatever), it's often useful to date or datetime stamp the data files or log coming out of the process.  Here is simple code that I use to generate date and datetime stamps in various languages that I use regularly: SAS, Perl, C#, and VB.NET.

I prefer stamps in yyyymmdd and yyyymmdd_hhmmss formats (yyyy=4-digit year, mm=2-digit month, dd=2-digit day, hh=hour on 24-hour clock, mm=minute, ss=second) since these are readily sortable in chronological order.

SAS

*Create a picture format for making datetime stamps;
proc format;
    picture dtstamp low-high='%Y%0m%d_%0H%0M%0S'
                    (datatype=datetime);
run;

*Create a date and a datetime stamp macro variable;
data _null_;
    *Use built in yyyymmdd format;
    call symput('datestamp',put(date(),yymmddn8.));     
    *Use custom picture format;
    call symput('datetimestamp',compress(put(datetime(),dtstamp.))); 
run;

%put FYI: datestamp=&datestamp;
%put FYI: datetimestamp=&datetimestamp;

*Sample usage;
data daily_extract_&datestamp;
    *blah blah blah;
run;
data hourly_extract_&datetimestamp;
    *blah blah blah;
run;

Log says...

FYI: datestamp=20120717
FYI: datetimestamp=20120717_103230

NOTE: The data set WORK.DAILY_EXTRACT_20120717 has 1 observations and 0 variables.
NOTE: The data set WORK.HOURLY_EXTRACT_20120717_103230 has 1 observations and 0 variables.

Obviously bundling that code up in a couple of macros (%datestamp and %datetimestamp) is the way to go.

Perl

use POSIX qw(strftime);
my $datestamp = strftime("%Y%m%d", localtime);
my $datetimestamp = strftime("%Y%m%d_%H%M%S", localtime);
print "FYI: datestamp=$datestamp\n";
print "FYI: datetimestamp=$datetimestamp\n";

Output...

FYI: datestamp=20120717
FYI: datetimestamp=20120717_103230

C#

string datestamp = DateTime.Now.ToString("yyyyMMdd");
string datetimestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
Console.WriteLine("FYI: datestamp={0}", datestamp);
Console.WriteLine("FYI: datetimestamp={0}", datetimestamp);

Output...

FYI: datestamp=20120717
FYI: datetimestamp=20120717_103230

VB.NET

Dim datestamp As String = DateTime.Now.ToString("yyyyMMdd")
Dim datetimestamp As String = DateTime.Now.ToString("yyyyMMdd_HHmmss")
Console.WriteLine("FYI: datestamp={0}", datestamp)
Console.WriteLine("FYI: datetimestamp={0}", datetimestamp)

Output...

FYI: datestamp=20120717
FYI: datetimestamp=20120717_103230

No comments:

Post a Comment