Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert UTC time to unix timestamp

Tags:

go

I am looking for an option to convert UTC time string to unix timestamp.

The string variable I have is 02/28/2016 10:03:46 PM and it needs to be converted to a unix timestamp like 1456693426

Any idea how to do that?

like image 585
user1813037 Avatar asked Feb 28 '16 21:02

user1813037


People also ask

How do you convert UTC to Unix?

We can do this by simply multiplying the Unix timestamp by 1000 . Unix time is the number of seconds that have elapsed since the Unix epoch, which is the time 00:00:00 UTC on 1 January 1970 .

Is Unix timestamp in UTC?

Unix timestamps are always based on UTC (otherwise known as GMT). It is illogical to think of a Unix timestamp as being in any particular time zone. Unix timestamps do not account for leap seconds.

How do I convert timestamp to time in Unix?

To convert a date to a Unix timestamp:Get a timestamp in milliseconds using the getTime() method. Convert the result to seconds by dividing by 1000 .

How do you convert UTC to Unix time in python?

DateTime to Unix timestamp in UTC Timezone In the time module, the timegm function returns a Unix timestamp. The timetuple() function of the datetime class returns the datetime's properties as a named tuple. To obtain the Unix timestamp, use print(UTC).


1 Answers

First of, the unix timestamp 1456693426 does not have the time 10:03:46 PM but 9:03:46 PM in UTC.

In the time package there is the function Parse with expects a layout to parse the time. The layout is constructed from the reference time Mon Jan 2 15:04:05 -0700 MST 2006. So in your case the layout would be 01/02/2006 3:04:05 PM. After using Parse you get a time.Time struct on which you can call Unix to receive the unix timestamp.

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "01/02/2006 3:04:05 PM"
    t, err := time.Parse(layout, "02/28/2016 9:03:46 PM")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t.Unix())
}
like image 199
Danilo Avatar answered Sep 20 '22 22:09

Danilo