Golang/Postgres Unix time

Ravil Akhtyamov
2 min readAug 27, 2020

Golang Unix time

Get unix time in the seconds/nanoseconds

t := time.Now().Unix()
//1597997012
t := time.Now().UnixNano()
//1597997681050794871

Convert unix time to time.Time in seconds/nanoseconds

t := time.Unix(1597997012, 0)
//2020-08-21 11:03:32 +0300 MSK
t := time.Unix(1597997012, 50794871)
//2020-08-21 11:03:32.050794871 +0300 MSK

Convert string(standart formats) to unix time

t, err := time.Parse(time.RFC3339, "2020-05-10T03:15:00Z")
if err != nil {
return
}
t.Unix()
//1589080500
t, err := time.Parse(time.RFC3339Nano, "2020-05-10T03:10:00.00000001Z")
if err != nil {
return
}
t.UnixNano()
//1589080200000000010

Unix time to string standart format

t := time.Unix(1597997012, 0)
t.Format(time.RFC3339)
//2020-08-21T08:03:32Z
t := time.Unix(1597997012, 50794871)
t.Format(time.RFC3339Nano)
//2020-08-21T08:03:32.050794871Z

Custom formats to unix time

A specific time is used to describe the format.
Year = 2006
Month = 01
Day = 02
Hour = 15
Minute = 04
Second = 05
Nanosecond = 0.999999999
Time Zone = 07:00

format := "Year=2006,Month=01,Day=02,Hour=15,Minute=04,Second=05"date :=  "Year=2020,Month=08,Day=25,Hour=11,Minute=34,Second=55"
t, err := time.Parse(format, date)
if err != nil {
return
}
t.Unix()
//1598355295
format := "Year=2006,Month=01,Day=02, Hour=15,Minute=04,Second=05,Nano=0.999999999"d:="Year=2020,Month=08,Day=25,Hour=11,Minute=34,Second=55,Nano=0.2"
t, err := time.Parse(f, d)
if err != nil {
return
}
t.UnixNano()
//1598355295200000000

Unix time to custom formats

format := "Year=2006,Month=01,Day=02,Hour=15,Minute=04,Second=05"t := time.Unix(1597997012, 0)
t.Format(format)
Year=2020,Month=08,Day=21,Hour=08,Minute=03,Second=32
format := "Year=2006,Month=01,Day=02, Hour=15,Minute=04,Second=05,Nano=0.999999999"t := time.Unix(1597997012, 200450000)
t.Format(f)
Year=2020,Month=08,Day=21,Hour=08,Minute=03,Second=32,Nano=0.20045

Postgres Unix time

Unix time to TimeStamp seconds/nanoseconds

to_timestamp(time::double precision / 1000)
//1601553074 -> 2020-10-01 11:24:05
to_timestamp(time::double precision / 1000000000)
//1601553073753999872 -> 2020-10-01 11:24:05.390583+03

TimeStamp to Unix time in seconds/nanoseconds

extract(epoch from created_at)::bigint
//2020-10-01 11:24:05 -> 1601553074
(extract(epoch from created_at)*1000000000)::bigint
//2020-10-01 11:24:05.390583+03-> 51601553073753999872

--

--