79

I would like to get the current timestamp and print it out using fprintf.

Xantium
  • 11,201
  • 10
  • 62
  • 89
Tim
  • 6,079
  • 8
  • 35
  • 41
  • 2
    Is there any particular reason why it needs to specifically be an int? – Dennis Meng Aug 01 '12 at 18:29
  • @DennisMeng If I had to guess, he probably wanted to get the timestamp as the return code and cut out output-handling. – kayleeFrye_onDeck Jan 07 '17 at 11:09
  • 2
    Sorry to necrobump this, but *technically* all of these answers are incorrect since `time` is **not** guaranteed to be since the Unix epoch; according to Wikipedia it can be any epoch that the vendor chooses. It also says 1900 is sometimes used. However, i would assume that it is since the Unix epoch on all even remotely sane systems. – markasoftware May 25 '17 at 01:10

5 Answers5

89

For 32-bit systems:

fprintf(stdout, "%u\n", (unsigned)time(NULL)); 

For 64-bit systems:

fprintf(stdout, "%lu\n", (unsigned long)time(NULL)); 
Dmitry Poroh
  • 3,705
  • 20
  • 34
  • 1
    What if I wanted it in microseconds? – Tim Aug 01 '12 at 21:26
  • 3
    If you want microseconds you should use one of this function: clock_gettime with CLOCK_MONOTONIC clock id or gettimeofday. But beware gettimeofday can return decreasing time values. – Dmitry Poroh Aug 01 '12 at 21:34
  • so you mean, gettimeofday could return N at time T, but return N-1 at time T+1 ? – Tim Aug 01 '12 at 23:47
  • yes, because the gettimeofday is real (wall-clock) time and it may be corrected by NTP or by user. – Dmitry Poroh Aug 02 '12 at 04:04
  • 1
    Note that time function (and clock_gettime with CLOCK_REALTIME id) is also returns wall clock time and can return decreasing timestamps. – Dmitry Poroh Aug 02 '12 at 04:56
  • 1
    You can avoid type casting by specifying proper conversion specification. You can learn what `time_t` (returned by `time`) resolves to by running preprocessor on your C file (`cpp main.c`). On my 64-bit system `time_t` is `long int`, which leads to `%ld` conversion specification. – x-yuri Oct 18 '17 at 20:39
  • 14
    `#include ` – Ben Sep 03 '18 at 19:10
46

Is just casting the value returned by time()

#include <stdio.h>
#include <time.h>

int main(void) {
    printf("Timestamp: %d\n",(int)time(NULL));
    return 0;
}

what you want?

$ gcc -Wall -Wextra -pedantic -std=c99 tstamp.c && ./a.out
Timestamp: 1343846167

To get microseconds since the epoch, from C11 on, the portable way is to use

int timespec_get(struct timespec *ts, int base)

Unfortunately, C11 is not yet available everywhere, so as of now, the closest to portable is using one of the POSIX functions clock_gettime or gettimeofday (marked obsolete in POSIX.1-2008, which recommends clock_gettime).

The code for both functions is nearly identical:

#include <stdio.h>
#include <time.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {

    struct timespec tms;

    /* The C11 way */
    /* if (! timespec_get(&tms, TIME_UTC)) { */

    /* POSIX.1-2008 way */
    if (clock_gettime(CLOCK_REALTIME,&tms)) {
        return -1;
    }
    /* seconds, multiplied with 1 million */
    int64_t micros = tms.tv_sec * 1000000;
    /* Add full microseconds */
    micros += tms.tv_nsec/1000;
    /* round up if necessary */
    if (tms.tv_nsec % 1000 >= 500) {
        ++micros;
    }
    printf("Microseconds: %"PRId64"\n",micros);
    return 0;
}
Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
  • 1
    What if I wanted it in microseconds? – Tim Aug 01 '12 at 21:26
  • That would mean that `int` is not the appropriate type on almost(?) all common systems. With typical `INT_MAX = 2147483647`, if you want microseconds, you can just fit a little less than 36 minutes into `int`. And of course, you generally can't use `time()` then. Portably, you'd have to use `timespec_get()` then. What is it that you want? Unix timestamp or microseconds (since epoch)? – Daniel Fischer Aug 01 '12 at 21:39
  • Microseconds since epoch would be the best. – Tim Aug 01 '12 at 23:47
  • Done microseconds, unfortunately I discovered that `timespec_get` is new in C11, so portability is an issue. – Daniel Fischer Aug 02 '12 at 00:27
14

With second precision, you can print tv_sec field of timeval structure that you get from gettimeofday() function. For example:

#include <sys/time.h>
#include <stdio.h>

int main()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    printf("Seconds since Jan. 1, 1970: %ld\n", tv.tv_sec);
    return 0;
}

Example of compiling and running:

$ gcc -Wall -o test ./test.c 
$ ./test 
Seconds since Jan. 1, 1970: 1343845834

Note, however, that its been a while since epoch and so long int is used to fit a number of seconds these days.

There are also functions to print human-readable times. See this manual page for details. Here goes an example using ctime():

#include <time.h>
#include <stdio.h>

int main()
{
    time_t clk = time(NULL);
    printf("%s", ctime(&clk));
    return 0;
}

Example run & output:

$ gcc -Wall -o test ./test.c 
$ ./test 
Wed Aug  1 14:43:23 2012
$ 
6
#include <stdio.h>
#include <time.h>

int main ()
{
   time_t seconds;

   seconds = time(NULL);
   printf("Seconds since January 1, 1970 = %ld\n", seconds);

   return(0);
}

And will get similar result:
Seconds since January 1, 1970 = 1476107865

Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45
1

An important point is to consider if you perform tasks based on difference between 2 timestamps because you will get odd behavior if you generate it with gettimeofday(), and even clock_gettime(CLOCK_REALTIME,..) at the moment where you will set the time of your system.

To prevent such problem, use clock_gettime(CLOCK_MONOTONIC_RAW, &tms) instead.

fralbo
  • 2,534
  • 4
  • 41
  • 73