Monday, January 21, 2013

gawk - Date and time calculation functions



gawk has 3 functions to calculate date and time:
  • systime
  • strftime
  • mktime
   Let us see in this article how to use these functions:

systime:
   This function is equivalent to the Unix date (date +%s) command. It gives the Unix time, total number of seconds elapsed since the epoch(01-01-1970 00:00:00).
$ echo | awk '{print systime();}'
1358146640
Note: systime function does not take any arguments.

strftime:
   A very common function used in gawk to format the systime into a calendar format. Using this function, from the systime, the year, month, date, hours, mins and seconds can be separated.

Syntax:
   strftime (<format specifiers>,unix time);
1. Printing current date time using strftime:
$ echo | awk '{print strftime("%d-%m-%y %H-%M-%S",systime());}'
14-01-13 12-37-45
   strftime takes format specifiers which are same as the format specifiers available with the date command. %d for date, %m for month number (1 to 12), %y for the 2 digit year number, %H for the hour in 24 hour format, %M for minutes and %S for seconds. In this way, strftime converts Unix time into a date string.

2. Display current date time using strftime without systime:
$ echo | awk '{print strftime("%d-%m-%y %H-%M-%S");}'
14-01-13 12-38-08
   Both the arguments of strftime are optional. When the timestamp is not provided, it takes the systime by default.

3. strftime with no arguments:
$ echo | awk '{print strftime();}'
Mon Jan 14 12:30:05 IST 2013
  strftime without the format specifiers provides the output in the default output format as the Unix date command.

mktime:
    mktime function converts any given date time string into a Unix time, which is of the systime format.
Syntax:
  mktime(date time string) # where date time string is a string which contains atleast 6 components in the following order: YYYY MM DD HH MM SS

1. Printing timestamp for a specific date time :
$ echo | awk '{print mktime("2012 12 21 0 0 0");}'
1356028200
     This gives the Unix time for the date 21-Dec-12.

2.  Using strftime with mktime:
$ echo | awk '{print strftime("%d-%m-%Y",mktime("2012 12 21 0 0 0"));}'
21-12-2012
   The output of mktime can be validated by formatting the mktime output using the strftime function as above.

3. Negative date in mktime:
$ echo | awk '{print strftime("%d-%m-%Y",mktime("2012 12 -1 0 0 0"));}'
29-11-2012
  mktime can take negative values as well. -1 in the date position indicates one day before the date specified which in this case leads to 29th Nov 2012.

4. Negative hour value in mktime:
$ echo | awk '{print strftime("%d-%m-%Y %H-%M-%S",mktime("2012 12 3 -2 0 0"));}'
02-12-2012 22-00-00
    -2 in the hours position indicates 2 hours before the specified date time which in this case leads to "2-Dec-2012 22" hours.

No comments:

Post a Comment