[unix] How can I generate Unix timestamps?

Related question is "Datetime To Unix timestamp", but this question is more general.

I need Unix timestamps to solve my last question. My interests are Python, Ruby and Haskell, but other approaches are welcome.

What is the easiest way to generate Unix timestamps?

This question is related to unix unix-timestamp

The answer is


For completeness, PHP:

php -r 'echo time();'

In BASH:

clitime=$(php -r 'echo time();')
echo $clitime

In Perl:

>> time
=> 1335552733

With NodeJS, just open a terminal and type:
node -e "console.log(new Date().getTime())" or node -e "console.log(Date.now())"


In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME

curl icanhazepoch.com

Basically it's unix timestamps as a service (UTaaS)


In python add the following lines to get a time stamp:

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993

If you need a Unix timestamp from a shell script (Bourne family: sh, ksh, bash, zsh, ...), this should work on any Unix machine as unlike the other suggestions (perl, haskell, ruby, python, GNU date), it is based on a POSIX standard command and feature.

PATH=`getconf PATH` awk 'BEGIN {srand();print srand()}'

Let's try JavaScript:

var t = Math.floor((new Date().getTime()) / 1000);

...or even nicer, the static approach:

var t = Math.floor(Date.now() / 1000);

In both cases I divide by 1000 to go from seconds to millis and I use Math.floor to only represent whole seconds that have passed (vs. rounding, which might round up to a whole second that hasn't passed yet).


in Haskell

import Data.Time.Clock.POSIX

main :: IO ()
main = print . floor =<< getPOSIXTime

in Go

import "time"
t := time.Unix()

in C

time(); // in time.h POSIX

// for Windows time.h
#define UNIXTIME(result)   time_t localtime; time(&localtime); struct tm* utctime = gmtime(&localtime); result = mktime(utctime);

in Swift

NSDate().timeIntervalSince1970 // or Date().timeIntervalSince1970

$ date +%s.%N

where (GNU Coreutils 8.24 Date manual)

  • +%s, seconds since 1970-01-01 00:00:00 UTC
  • +%N, nanoseconds (000000000..999999999) since epoch

Example output now 1454000043.704350695. I noticed that BSD manual of date did not include precise explanation about the flag +%s.


If I want to print utc date time using date command I need to using -u argument with date command.

Example

date -u

Output

Fri Jun 14 09:00:42 UTC 2019

In Haskell...

To get it back as a POSIXTime type:

import Data.Time.Clock.POSIX
getPOSIXTime

As an integer:

import Data.Time.Clock.POSIX
round `fmap` getPOSIXTime

The unix 'date' command is surprisingly versatile.

date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"

Takes the output of date, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.


in Ruby:

>> Time.now.to_i
=> 1248933648

public static Int32 GetTimeStamp()
    {
        try
        {
            Int32 unixTimeStamp;
            DateTime currentTime = DateTime.Now;
            DateTime zuluTime = currentTime.ToUniversalTime();
            DateTime unixEpoch = new DateTime(1970, 1, 1);
            unixTimeStamp = (Int32)(zuluTime.Subtract(unixEpoch)).TotalSeconds;
            return unixTimeStamp;
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
            return 0;
        }
    }

First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.

Generating the current time in Perl is rather easy:

perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime() function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

nawk:

$ nawk 'BEGIN{print srand()}'
  • Works even on old versions of Solaris and probably other UNIX systems, where '''date +%s''' isn't implemented
  • Doesn't work on Linux and other distros where the posix tools have been replaced with the GNU versions (nawk -> gawk etc.)
  • Pretty unintuitive but definitelly amusing :-)