339

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?

Community
  • 1
  • 1
Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
  • @A.B.Carroll Can you please explain as an anwer how your online tool provides Unix timestamps? Please, attach a manual etc for it. It seems to provide a lot of data but I cannot really follow what is the target. – Léo Léopold Hertz 준영 Jun 15 '17 at 09:23
  • `gettimeofday` is the POSIX and Linux syscall name: https://stackoverflow.com/questions/11765301/how-do-i-get-the-unix-timestamp-in-c-as-an-int/11765379#11765379 TODO: why `strace date +%d` not call it? – Ciro Santilli OurBigBook.com Oct 07 '17 at 02:56
  • If you work with, and increment time ranges (e.g. minutes, days, hours), I wrote a tool for my own use recently https://unixtime.ninja – Guy Thouret Mar 26 '19 at 09:48

20 Answers20

681

In Linux or MacOS you can use:

date +%s

where

  • +%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.

Jason
  • 9,408
  • 5
  • 36
  • 36
Naresh
  • 1
  • 1
  • 3
  • 2
  • 1
    On Solaris: truss date 2>&1 | grep ^time | awk '{print $3}' – Ľubomír Mlích Dec 15 '16 at 05:54
  • 1
    BSD date supports also +%s. Probably universal, as `date` is normally defined in POSIX.2. – Dereckson Nov 05 '17 at 15:41
  • @ĽubomírMlích On a SmartOS host (SunOS 5.11 joyent_20171026T003127Z), I've both `/usr/bin/date +%s and `/usr/xpg4/bin/date +%s` working. Combined with the POSIX.2 recommendation, I think this works on all Solaris too. – Dereckson Nov 05 '17 at 17:21
  • Note: to add 60 seconds: `date -v+60S +%s` to add 1 day: `date -v+24H +%s` and so on . . . – gMale May 24 '18 at 22:00
  • How to generate milliseconds upto 3 digit only ? – Parveen Verma Sep 21 '18 at 10:12
  • One liner for Fish shell users who want a `ut` command that copies to clipboard: `abbr --add ut "date +%s | xsel --clipboard"` (may have to install `xsel` package. ut = unixtime, you could also use the latter. – Elijah Lynn Dec 19 '19 at 01:22
  • If you'd like to show timestamp till specific day, we can use: `date +%s -d YYYYMMDD` (Replace YYYY MM DD with year, month, and day) – Bin S Jul 12 '21 at 03:07
111

in Ruby:

>> Time.now.to_i
=> 1248933648
bb.
  • 1,371
  • 1
  • 14
  • 21
20

curl icanhazepoch.com

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

Hut8
  • 6,080
  • 4
  • 42
  • 59
  • 4
    Heh, nice. This inspired me to add a similar feature to my hobby site. `curl -L -H "Accept: application/json" unixtimesta.mp` will give you `{"datetime":"Thu, 19 Jul 2018 12:01:21 GMT","timestamp":1532001681}` – Craig Anderson Jul 19 '18 at 12:01
  • 4
    Service [offline](https://major.io/2022/07/28/extra-icanhazip-services-going-offline/) since 17th august 2022 – ntippman Jan 09 '23 at 10:48
19

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

>>> import time
>>> time.time()
1335906993.995389
>>> int(time.time())
1335906993
shobhit_mittal
  • 113
  • 2
  • 5
Steven Kryskalla
  • 14,179
  • 2
  • 40
  • 42
19
$ 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.

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
Lydia
  • 2,377
  • 16
  • 13
17

In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME
Colera Su
  • 193
  • 1
  • 5
  • I think this one is the most useful of all I've seen – Dmitry Gashko Jul 21 '22 at 21:05
  • In case of `zsh` one may need to load the `zsh/datetime` module (https://zsh.sourceforge.io/Doc/Release/Zsh-Modules.html#The-zsh_002fdatetime-Module) using the command `zmodload zsh/datetime` before being able to use these variables. – Victor Yarema Feb 22 '23 at 17:38
12

In Perl:

>> time
=> 1335552733
davidchambers
  • 23,918
  • 16
  • 76
  • 105
9

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.

Alan Horn
  • 80
  • 1
  • 2
7

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"'
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
5

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
Community
  • 1
  • 1
ZagNut
  • 1,431
  • 15
  • 20
4

For completeness, PHP:

php -r 'echo time();'

In BASH:

clitime=$(php -r 'echo time();')
echo $clitime
Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
  • 1
    for bash we already have the `date` command, so I don't think it is necessary to call php from there. – fedorqui Jul 28 '15 at 15:36
2

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
Tom Morris
  • 3,979
  • 2
  • 25
  • 43
2
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;
        }
    }
2

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).

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • 1
    This is wrong. Both methods return `milliseconds` not seconds and unix timestamp is the number of `seconds` that have elapsed since January 1, 1970 00:00 UTC. You can use JS, just divide by 1000 and round: `Math.round(Date.now()/1000)` – Lukas Liesis Jun 06 '18 at 20:17
  • 1
    @LukasLiesis must've been pre-coffee that day, I've updated my answer although I opted for `Math.floor` instead of `Math.round`. Cheers – Madbreaks Jun 06 '18 at 21:14
2

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
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29
1

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 :-)
pez
  • 11
  • 2
1

For Unix-like environment the following will work.

# Current UNIXTIME
unixtime() {
  datetime2unixtime "$(date -u +'%Y-%m-%d %H:%M:%S')"
}

# From DateTime(%Y-%m-%d %H:%M:%S)to UNIXTIME
datetime2unixtime() {
  set -- "${1%% *}" "${1##* }"
  set -- "${1%%-*}" "${1#*-}" "${2%%:*}" "${2#*:}"
  set -- "$1" "${2%%-*}" "${2#*-}" "$3" "${4%%:*}" "${4#*:}"
  set -- "$1" "${2#0}" "${3#0}" "${4#0}" "${5#0}" "${6#0}"
  [ "$2" -lt 3 ] && set -- $(( $1-1 )) $(( $2+12 )) "$3" "$4" "$5" "$6"
  set -- $(( (365*$1)+($1/4)-($1/100)+($1/400) )) "$2" "$3" "$4" "$5" "$6"
  set -- "$1" $(( (306*($2+1)/10)-428 )) "$3" "$4" "$5" "$6"
  set -- $(( ($1+$2+$3-719163)*86400+$4*3600+$5*60+$6 ))
  echo "$1"
}

# From UNIXTIME to DateTime format(%Y-%m-%d %H:%M:%S)
unixtime2datetime() {
  set -- $(( $1%86400 )) $(( $1/86400+719468 )) 146097 36524 1461
  set -- "$1" "$2" $(( $2-(($2+2+3*$2/$3)/$5)+($2-$2/$3)/$4-(($2+1)/$3) ))
  set -- "$1" "$2" $(( $3/365 ))
  set -- "$@" $(( $2-( (365*$3)+($3/4)-($3/100)+($3/400) ) ))
  set -- "$@" $(( ($4-($4+20)/50)/30 ))
  set -- "$@" $(( 12*$3+$5+2 ))
  set -- "$1" $(( $6/12 )) $(( $6%12+1 )) $(( $4-(30*$5+3*($5+4)/5-2)+1 ))
  set -- "$2" "$3" "$4" $(( $1/3600 )) $(( $1%3600 ))
  set -- "$1" "$2" "$3" "$4" $(( $5/60 )) $(( $5%60 ))
  printf "%04d-%02d-%02d %02d:%02d:%02d\n" "$@"
}

# Examples
unixtime # => Current UNIXTIME
date +%s # Linux command

datetime2unixtime "2020-07-01 09:03:13" # => 1593594193
date -u +%s --date "2020-07-01 09:03:13" # Linux command

unixtime2datetime "1593594193" # => 2020-07-01 09:03:13
date -u --date @1593594193 +"%Y-%m-%d %H:%M:%S" # Linux command

https://tech.io/snippet/a3dWEQY

shin
  • 31,901
  • 69
  • 184
  • 271
0

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

Dusan Jovanov
  • 547
  • 5
  • 21
0

In Rust:

use std::time::{SystemTime, UNIX_EPOCH};


fn main() {
    let now = SystemTime::now();
    println!("{}", now.duration_since(UNIX_EPOCH).unwrap().as_secs())
}
Steve Lau
  • 658
  • 7
  • 13
-1

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()}'
jlliagre
  • 29,783
  • 6
  • 61
  • 72