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?
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 .
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.
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 .
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).
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())
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With