How to convert UTC time to unix timestamp - 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?

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())
}

Related

How to parse time using a specific timezone

I am to get a time struct from a string. I am using the function time.ParseTime() with the layout "2006-01-02 15:04".
When I execute the function with any valid time string I get a time struct pointing to that time stamp but it is in UTC.
How can I change it to a different time zone? To be clear I want the same timestamp but with a different time zone. I don't want to convert between timezones; I just want to get the same time object but not in UTC.
Use time.ParseInLocation to parse time in a given Location when there's no time zone given. time.Local is your local time zone, pass that in as your Location.
package main
import (
"fmt"
"time"
)
func main() {
// This will honor the given time zone.
// 2012-07-09 05:02:00 +0000 CEST
const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
fmt.Println(t)
// Lacking a time zone, it will use your local time zone.
// Mine is PDT: 2012-07-09 05:02:00 -0700 PDT
const formWithoutZone = "Jan 2, 2006 at 3:04pm"
t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
fmt.Println(t)
}

Subtracting time to get age

My aim is to calculate the age of the pod by doing the subtraction of "current_time - pod_creation_time" so that I will get the age, I am getting creation time from metadata but it's in the format "2021-07-13 16:34:22 +0530 IST", so when I trying to subtract it from time.Now(), I am getting parsing error like below:
invalid operation: "t2 : " + t2 (mismatched types string and time.Time)
Anyone could please help how to have creation time "2021-07-13 16:34:22 +0530 IST" from metadata in the proper format so that I can do "time.Now - (creation time)"
I tried some workaround like below:
creatTime, err := time.Parse("2006-01-02 15:04:05 -0700 MST",
pod.ObjectMeta.CreationTimestamp.String())
and then subtracted creationTime from Current Time. It works, but I think this is not the right way.
There's a type mismatch as time.Now() return the current time stored in the type time.Time whereas 2021-07-13 16:34:22 +0530 IST is a string. You can perform the required subtraction operation on mismatched types i.e., time.Time and string.
You have to parse the string by specifying the layout. I'd recommend reading the time package's doc.
I've explained every operation in the sample code below; I hope it helps. If you understand this, you can also then look at helper functions like time.Since that can help you write the same program in fewer lines.
package main
import (
"fmt"
"time"
)
func main() {
// K8s timestamp
t := "2021-07-13 16:34:22 +0530 IST"
// Format of K8s timestamp
format := "2006-01-02 15:04:05 -0700 MST" // Mon Jan 2 15:04:05 -0700 MST 2006
// Parse the timestamp so that it's stored in time.Time
cur, err := time.Parse(format, t)
if err != nil {
panic(err)
}
// Current time
now := time.Now()
// As both are of type time.Time, it's subtractable
dur := now.Sub(cur)
// Print duration
fmt.Println(dur)
// Print duration (in seconds)
fmt.Println(dur.Seconds())
}
Also, I'd like you to learn how to write questions on StackOverflow. The formatting of your question is pretty bad. When seeking good solutions; it is the OP's duty to post the question correctly first so that everybody could understand it and then expect answers.
Read: https://stackoverflow.com/help/how-to-ask

IST time zone error in time package go golang

I need to convert any given time zone in RFC3339 format to system time in RFC3339 format.But for few time zone like IST it is throwing the error and the time is still in UTC.
For conversion which function service as better? time.parse or time.In.
I tried to convert the UTC to IST but it failed.
package main
import (
"fmt"
"time"
)
func main() {
//now time
now := time.Now()
fmt.Println("now ", now)
zone, _ := now.Zone()
fmt.Println("zone->", zone)
ll, llerr := time.LoadLocation(zone)
fmt.Println("Load Location", ll, llerr)
// Convert the given time to system based time zone
t, err := time.ParseInLocation(time.RFC3339, "2017-04-25T23:03:00Z", ll)
fmt.Println("t - parsein", t)
fmt.Println("err - parsein", err)
//fmt.Println("t2 - parse", t.In(ll))
}
Error : unknown time zone IST
Expected: Need to convert any time zone to system time zone.
You can't load Indian IST time zone by that name because the name "IST" is ambiguous. It could mean India, Ireland, Israel, etc. time zones, which have different zone offsets and rules. For details, see Why is time.Parse not using the timezone?
If IST is your local zone, the time.Local variable will denote that time zone. If you have a time.Time, you can "switch" to another zone using Time.In(), also Time.Local() returns the time in your local zone.
Of course this code would "break" when ran in another zone. To make sure it behaves the same everywhere, load the Indian IST zone explicitly like this:
loc, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
panic(err)
}
fmt.Println(time.Now())
fmt.Println(time.Now().In(loc))
On the Go Playground it will output:
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-11-11 04:30:00 +0530 IST

Go: How to parse only date to time.Time?

I want to parse only date value to time.Time.
For example I have date in this format: 2016-03-31, and I want to parse it, like: time.Parse(FORMAT, "2016-03-31").
But it always fail.
What is the correct format string to use to parse only date with this format?
I have the code below as example, it is on playground also: https://play.golang.org/p/0MNLr9emZd
package main
import (
"fmt"
"time"
)
var dateToParse = "2016-03-31"
func main() {
format := "2006-12-01"
parseDate(format)
}
func parseDate(format string) {
t, err := time.Parse(format, dateToParse)
if err != nil {
fmt.Println("Format:", format)
fmt.Println(err)
fmt.Println("")
return
}
fmt.Println("Works Format:", format)
fmt.Println(t)
fmt.Println("")
}
The output is this:
Format: 2006-12-01
parsing time "2016-03-31" as "2006-12-01": cannot parse "-31" as "2"
Package time
These are predefined layouts for use in Time.Format and Time.Parse.
The reference time used in the layouts is the specific time:
Mon Jan 2 15:04:05 MST 2006
which is Unix time 1136239445. Since MST is GMT-0700, the reference
time can be thought of as
01/02 03:04:05PM '06 -0700
To define your own format, write down what the reference time would
look like formatted your way; see the values of constants like ANSIC,
StampMicro or Kitchen for examples.
Use format := "2006-01-02" for yyyy-mm-dd.
The new format DateOnly = "2006-01-02" of format.go will be added in the Go next release (1.20) per proposal time: add DateTime, DateOnly, TimeOnly format constants and commit
time.Parse(time.DateOnly, dateToParse)

How to use time.Parse to parse hh:mm format in Go

I am importing a lot of fields of the format:
09:02 AM
10:02 AM
12:30 PM
04:10 PM
04:50 PM
05:30 PM
I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs. Thus, saving the field in microseconds... or even seconds.
I have been trying to get the time.Parse to work... no joy.
fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))
returns...
0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"
any suggestions?
The layout string for time.Parse does not handle the "hh:mm" format. In your case, the layout string would rather be "03:04 PM" as you can see in the documentation.
To get a time.Duration after parsing the string, you can substract your time with a reference time, in your case I would assume "12:00 AM".
Working example:
package main
import (
"fmt"
"time"
)
func main() {
ref, _ := time.Parse("03:04 PM", "12:00 AM")
t, err := time.Parse("03:04 PM", "11:22 PM")
if err != nil {
panic(err)
}
fmt.Println(t.Sub(ref).Seconds())
}
Output:
84120
Playground
Did you read the documentation of time.Parse? In the very beginning it says:
The layout defines the format by showing how the reference time,
defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted
if it were the value
In the beginning of the package documentation there are more details about the layout string. Note that you can omit some of the fields (in your case days, years and timezeone) and those will then always get zero value.
So fmt.Println(time.Parse("3:04 PM", "07:50 PM")) should work.
If you'll check again the documentation about time's Parse method you'll find the fact that Go's approach of parsing the time is totally different than the one that you used to work with in other programming languages. To provide the Parse function the layout of the time that you want to parse you need to transform one specific date (which is Mon Jan 2 15:04:05 -0700 MST 2006) into the layout that you're aiming for. In your case that would be "03:04 PM".
The full code: fmt.Println(time.Parse("03:04 PM", m.Feed.Entry[i].GsxA100Time.T))
Just in case anyone is working with epoch times can use this,
func convert (in int64) string {
u := time.Unix(in/1000, in%1000)
ampm := "AM"
if u.Hour()/12 ==1 { ampm = "PM" }
th := u.Hour()%12
hh := strconv.Itoa(th)
if th < 10 { hh = "0" + hh }
tm := u.Minute()
mm := strconv.Itoa(tm)
if tm < 10 { mm = "0" + mm }
return hh + ":" + mm + " " + ampm
}

Resources