Sponsored Content
Full Discussion: subtract minutes from time
Top Forums Shell Programming and Scripting subtract minutes from time Post 302415025 by fpmurphy on Wednesday 21st of April 2010 02:15:22 PM
Old 04-21-2010
If you are using ksh93 the following works
Code:
printf "%(%Y%m%d%H%M%S)T" "${D:0:4}-${D:4:2}-${D:6:2} ${D:8:2}:${D:10:2}:${D:12:2} 2 minutes ago"

If neither GNU date or ksh93 are available to you the following short C utility will do the job
(see usage string for arguments):
Code:
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>


int
main(int argc, char* argv[])
{
   struct tm tm1, *tm2;

   char buf[80];
   char format[50];
   char tmp[80];
   char date[80];
   char seconds[10];
   char *s, *d;

   time_t t1, t2;

   int c;
   int debug = 0;
   int errflg = 0;

   extern char *optarg;
   extern int optind, optopt;

   while ((c = getopt(argc, argv, "dh")) != -1) {
        switch(c) {
        case 'd':
            debug = 1;
            break;
        case 'h':
            errflg++;
            break;
        case '?':
            fprintf(stderr, "Unknown option: -%c\n", optopt);
            errflg++;
        }
   }
   if (errflg || (argc < 2)) {
       fprintf(stderr, "Usage: subtime [-d] datestr seconds\n");
       exit(1);
   }

   strcpy(tmp, argv[optind]);
   optind++;
   strcpy(seconds, argv[optind]);

   strcpy(format, "%Y %m %d %H %M %S");

   /* reformat date string to place a space betwen each token */
   /* strptime specification requires a space */
   s = tmp;
   d = date;
   c = 0;
   while(*s) {
      if (c == 4 || c == 6 || c == 8 || c == 10 || c == 12 || c == 14) {
         *d++ = ' ';
      }
      c++;
      *d++ = *s++;
   }
   *d = '\0';

   if (debug) {
       fprintf(stderr, "Format: %s\n", format);
       fprintf(stderr, "Date: %s\n", date);
       fprintf(stderr, "Seconds: %s\n", seconds);
   }

   if (!strptime(date, format, &tm1)) {
       fprintf(stderr, "strptime() error\n");
       exit(1);
   }
   strftime(buf, 50, "%a %Y %H:%M:%S", &tm1);

   if ((t1 = mktime(&tm1)) == -1) {
      fprintf(stderr, "mktime() error\n");
      exit(1);
   }

   t1 = t1 - atoi(seconds);
   tm2 = localtime(&t1);

   if (strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", tm2) == 0) {
      fprintf(stderr, "strftime() error\n");
      exit(1);
   }

   printf("%s", buf);

   exit(0);
}

 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Subtract Time

Hello, Im writing a script using the ksh shell. I have 2 variables in the script: CURRTIME PREVTIME Example, if CURRTIME=13:00, I want to somehow calculate what the time was an hour ago so that PREVTIME=12:00 Right now I have the following: CURRTIME=`date +%H:%M` How can I... (4 Replies)
Discussion started by: xadamz23
4 Replies

2. Shell Programming and Scripting

Add/Subtract Time

need some help on the below requirement: File1: SV,22,20100501140000,JFK,RUH SV,29,20100501073000,BOM,RUH SV,29,20100501073000,SIN,RUH third filed is datetime which is of the format (yyyymmddhh24miss) File2 JFK,+,0500 BLR,-,0530 SIN,-,0800 for every line of file 1, take 4... (9 Replies)
Discussion started by: ssantoshss
9 Replies

3. Shell Programming and Scripting

Perl - Extract 12 hour time, convert to 24 and subtract 15 minutes?

OK, I am by no means a programmer... I have been given the task to do some automation scripts. I have got most of it working from snippets I have found on the Web. One requirement has me stumped. The initial timing file created by the user is a comma delimited in the following format.... (4 Replies)
Discussion started by: autotuner
4 Replies

4. Shell Programming and Scripting

How to subtract time by 10 minutes in datecalc tool

Hi guys. I am trying to subtract 10 minutes from the current Unix system date and time. I have the datecalc provided here but it is mainly the date and not the time. Please check on how can i subtract 10 minutes from the current time using datecalc or any other shell scripting that will... (2 Replies)
Discussion started by: bantiloe
2 Replies

5. Shell Programming and Scripting

Subtract two rows (in Time format)

Hello all, I have written sth like this: #!/bin/bash grep -e XXX -e YYYY myfile.log | grep -v ZZZ | awk '{print $1 " " $2 ";" $3 ";" $9 ";" $11}' > myfile.csv sed -i '1iDate;Time;From;To' myfile.csv => it is clear that it converts log to csv and add a header. Now I want to subtract row... (4 Replies)
Discussion started by: frhling
4 Replies

6. Shell Programming and Scripting

Add or Subtract the hours,minutes or seconds in the the time variable

Hello All, I am working on script where I need to add hours,minutes or seconds in the time.Time is not the current but it could be future time.I thought I can store that time in variable and add hours.minutes or second but I am not able to add that in the time that is stores in a variable. Time... (9 Replies)
Discussion started by: anuragpgtgerman
9 Replies

7. Shell Programming and Scripting

Date command - subtract from given time

the given time is: 12:13:00 how do i subtract a 10 minutes from any given time? date '12:13:00' '-10 min' also tried this: date +12:13:00 '-10 min' (2 Replies)
Discussion started by: SkySmart
2 Replies

8. UNIX for Dummies Questions & Answers

Subtract minutes from date

Hi, I am reading a particular date from a file using below command WFLWDATE=$(sed '2q;d' FileA.prm) The echo command outputs the correct date in variable WFLWDATE Now I want to subtract 5 minutes from this variable. I am on AIX and unable to get anything working as expected. Can you... (1 Reply)
Discussion started by: vrupatel
1 Replies

9. Shell Programming and Scripting

Subtract time in two line

INPUT: 16:45:51 10051 77845 16:45:51 10051 77845 16:46:52 10051 77846 16:46:53 10051 77846 Match the last PID then subtract second line time with first line. Please help me with any command or script. (3 Replies)
Discussion started by: vivekn
3 Replies

10. Shell Programming and Scripting

Check file creation Time minutes and if file older then 5 minutes execute some stuff

Hello all, Info: System RedHat 7.5 I need to create a script that based on the creation time, if the file is older then 5 minutes then execute some stuff, if not exit. I thought to get the creation time and minutes like this. CreationTime=$(stat -c %y /tmp/test.log | awk -F" " '{ print... (3 Replies)
Discussion started by: charli1
3 Replies
GETOPT(P)						     POSIX Programmer's Manual							 GETOPT(P)

NAME
getopt, optarg, opterr, optind, optopt - command option parsing SYNOPSIS
#include <unistd.h> int getopt(int argc, char * const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; DESCRIPTION
The getopt() function is a command-line parser that shall follow Utility Syntax Guidelines 3, 4, 5, 6, 7, 9, and 10 in the Base Definitions volume of IEEE Std 1003.1-2001, Section 12.2, Utility Syntax Guidelines. The parameters argc and argv are the argument count and argument array as passed to main() (see exec() ). The argument optstring is a string of recognized option characters; if a character is followed by a colon, the option takes an argument. All option characters allowed by Utility Syntax Guideline 3 are allowed in optstring. The implementation may accept other characters as an extension. The variable optind is the index of the next element of the argv[] vector to be processed. It shall be initialized to 1 by the system, and getopt() shall update it when it finishes with each element of argv[]. When an element of argv[] contains multiple option characters, it is unspecified how getopt() determines which options have already been processed. The getopt() function shall return the next option character (if one is found) from argv that matches a character in optstring, if there is one that matches. If the option takes an argument, getopt() shall set the variable optarg to point to the option-argument as follows: 1. If the option was the last character in the string pointed to by an element of argv, then optarg shall contain the next element of argv, and optind shall be incremented by 2. If the resulting value of optind is greater than argc, this indicates a missing option- argument, and getopt() shall return an error indication. 2. Otherwise, optarg shall point to the string following the option character in that element of argv, and optind shall be incremented by 1. If, when getopt() is called: argv[optind] is a null pointer* argv[optind] is not the character - argv[optind] points to the string "-" getopt() shall return -1 without changing optind. If: argv[optind] points to the string "--" getopt() shall return -1 after incrementing optind. If getopt() encounters an option character that is not contained in optstring, it shall return the question-mark ( '?' ) character. If it detects a missing option-argument, it shall return the colon character ( ':' ) if the first character of optstring was a colon, or a ques- tion-mark character ( '?' ) otherwise. In either case, getopt() shall set the variable optopt to the option character that caused the error. If the application has not set the variable opterr to 0 and the first character of optstring is not a colon, getopt() shall also print a diagnostic message to stderr in the format specified for the getopts utility. The getopt() function need not be reentrant. A function that is not required to be reentrant is not required to be thread-safe. RETURN VALUE
The getopt() function shall return the next option character specified on the command line. A colon ( ':' ) shall be returned if getopt() detects a missing argument and the first character of optstring was a colon ( ':' ). A question mark ( '?' ) shall be returned if getopt() encounters an option character not in optstring or detects a missing argument and the first character of optstring was not a colon ( ':' ). Otherwise, getopt() shall return -1 when all command line options are parsed. ERRORS
No errors are defined. The following sections are informative. EXAMPLES
Parsing Command Line Options The following code fragment shows how you might process the arguments for a utility that can take the mutually-exclusive options a and b and the options f and o, both of which require arguments: #include <unistd.h> int main(int argc, char *argv[ ]) { int c; int bflg, aflg, errflg; char *ifile; char *ofile; extern char *optarg; extern int optind, optopt; . . . while ((c = getopt(argc, argv, ":abf:o:")) != -1) { switch(c) { case 'a': if (bflg) errflg++; else aflg++; break; case 'b': if (aflg) errflg++; else { bflg++; bproc(); } break; case 'f': ifile = optarg; break; case 'o': ofile = optarg; break; case ':': /* -f or -o without operand */ fprintf(stderr, "Option -%c requires an operand ", optopt); errflg++; break; case '?': fprintf(stderr, "Unrecognized option: -%c ", optopt); errflg++; } } if (errflg) { fprintf(stderr, "usage: . . . "); exit(2); } for ( ; optind < argc; optind++) { if (access(argv[optind], R_OK)) { . . . } This code accepts any of the following as equivalent: cmd -ao arg path path cmd -a -o arg path path cmd -o arg -a path path cmd -a -o arg -- path path cmd -a -oarg path path cmd -aoarg path path Checking Options and Arguments The following example parses a set of command line options and prints messages to standard output for each option and argument that it encounters. #include <unistd.h> #include <stdio.h> ... int c; char *filename; extern char *optarg; extern int optind, optopt, opterr; ... while ((c = getopt(argc, argv, ":abf:")) != -1) { switch(c) { case 'a': printf("a is set "); break; case 'b': printf("b is set "); break; case 'f': filename = optarg; printf("filename is %s ", filename); break; case ':': printf("-%c without filename ", optopt); break; case '?': printf("unknown arg %c ", optopt); break; } } Selecting Options from the Command Line The following example selects the type of database routines the user wants to use based on the Options argument. #include <unistd.h> #include <string.h> ... char *Options = "hdbtl"; ... int dbtype, i; char c; char *st; ... dbtype = 0; while ((c = getopt(argc, argv, Options)) != -1) { if ((st = strchr(Options, c)) != NULL) { dbtype = st - Options; break; } } APPLICATION USAGE
The getopt() function is only required to support option characters included in Utility Syntax Guideline 3. Many historical implementations of getopt() support other characters as options. This is an allowed extension, but applications that use extensions are not maximally por- table. Note that support for multi-byte option characters is only possible when such characters can be represented as type int. RATIONALE
The optopt variable represents historical practice and allows the application to obtain the identity of the invalid option. The description has been written to make it clear that getopt(), like the getopts utility, deals with option-arguments whether separated from the option by <blank>s or not. Note that the requirements on getopt() and getopts are more stringent than the Utility Syntax Guide- lines. The getopt() function shall return -1, rather than EOF, so that <stdio.h> is not required. The special significance of a colon as the first character of optstring makes getopt() consistent with the getopts utility. It allows an application to make a distinction between a missing argument and an incorrect option letter without having to examine the option letter. It is true that a missing argument can only be detected in one case, but that is a case that has to be considered. FUTURE DIRECTIONS
None. SEE ALSO
exec() , the Base Definitions volume of IEEE Std 1003.1-2001, <unistd.h>, the Shell and Utilities volume of IEEE Std 1003.1-2001 COPYRIGHT
Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2003 Edition, Standard for Information Technol- ogy -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 6, Copyright (C) 2001-2003 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html . IEEE
/The Open Group 2003 GETOPT(P)
All times are GMT -4. The time now is 01:00 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy