Tag Archives: timestamp

Get Unix timestamp in Java, Python, Ruby, Erlang, JavaScript, Go, MySQL

Mostly a note for myself. To Get Unix timestamp value in seconds

Java:

long timestamp = System.currentTimeMillis()/1000

Python:

import time
timestamp = int(time.time())

JavaScript:

var ts = Math.floor(Date.now()/1000); // You can also use new Date().getTime()/1000 but this one is faster

Ruby:

require 'time'
ts = Time.now.to_f

Go:

package main
import (
 "time"
 "fmt"
)

func main() {
 // Get and print integer timestamp
 timestamp := time.Now().Unix()
 fmt.Printf("unixtime: %d\n", timestamp)
 // get and print floating point timestamp with sub-second precision
 timestampFloat := float64(time.Now().UnixNano()) / 1.0e9
 fmt.Printf("unixtime: %f\n", timestampFloat)
//Convert integer timestamp back to Time:
 t1 := time.Unix(timestamp, 0)
 fmt.Printf("Time: %v\n", t1)</pre>
//Convert floating point timestamp back to Time
 t2 := time.Unix(int64(timestampFloat), int64((timestampFloat - float64(int64(timestampFloat)))*1e9))
 fmt.Printf("Time: %v\n", t2)
 }

Erlang:

{Mega, Secs, _} = now(),
Timestamp = Mega*1000000 + Secs,

Working with timestamps in MySQL


mysql> SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');
-> 875996580
mysql> SELECT FROM_UNIXTIME(1111885200);
+---------------------------+
| FROM_UNIXTIME(1111885200) |
+---------------------------+
| 2005-03-27 03:00:00 |
+---------------------------+