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 |
+---------------------------+

Advertisements

13 thoughts on “Get Unix timestamp in Java, Python, Ruby, Erlang, JavaScript, Go, MySQL

  1. Nik

    The java method and the mysql method are inaccurate with each other. I’m using mysql server 5.0 and they often give results that are 1 hour apart (something to do with daylight savings time). WEEEAAAK

    Reply
  2. Pingback: Python e Datas | Ajudante de Programador

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s