How to get time without timezone? [duplicate] - go

I'm trying to add some values from my database to a []string in Go. Some of these are timestamps.
I get the error:
cannot use U.Created_date (type time.Time) as type string in array element
Can I convert time.Time to string?
type UsersSession struct {
Userid int
Timestamp time.Time
Created_date time.Time
}
type Users struct {
Name string
Email string
Country string
Created_date time.Time
Id int
Hash string
IP string
}
-
var usersArray = [][]string{}
rows, err := db.Query("SELECT u.id, u.hash, u.name, u.email, u.country, u.IP, u.created_date, us.timestamp, us.created_date FROM usersSession AS us LEFT JOIN users AS u ON u.id = us.userid WHERE us.timestamp + interval 30 minute >= now()")
U := Users{}
US := UsersSession{}
for rows.Next() {
err = rows.Scan(&U.Id, &U.Hash, &U.Name, &U.Email, &U.Country, &U.IP, &U.Created_date, &US.Timestamp, &US.Created_date)
checkErr(err)
userid_string := strconv.Itoa(U.Id)
user := []string{userid_string, U.Hash, U.Name, U.Email, U.Country, U.IP, U.Created_date, US.Timestamp, US.Created_date}
// -------------
// ^ this is where the error occurs
// cannot use U.Created_date (type time.Time) as type string in array element (for US.Created_date and US.Timestamp aswell)
// -------------
usersArray = append(usersArray, user)
log.Print("usersArray: ", usersArray)
}
EDIT
I added the following. It works now, thanks.
userCreatedDate := U.Created_date.Format("2006-01-02 15:04:05")
userSessionCreatedDate := US.Created_date.Format("2006-01-02 15:04:05")
userSessionTimestamp := US.Timestamp.Format("2006-01-02 15:04:05")

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".
If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".
Example:
t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))
Output (try it on the Go Playground):
2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00
Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.
Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():
Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be
Mon Jan 2 15:04:05 -0700 MST 2006
would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

package main
import (
"fmt"
"time"
)
// #link https://golang.org/pkg/time/
func main() {
//caution : format string is `2006-01-02 15:04:05.000000000`
current := time.Now()
fmt.Println("origin : ", current.String())
// origin : 2016-09-02 15:53:07.159994437 +0800 CST
fmt.Println("mm-dd-yyyy : ", current.Format("01-02-2006"))
// mm-dd-yyyy : 09-02-2016
fmt.Println("yyyy-mm-dd : ", current.Format("2006-01-02"))
// yyyy-mm-dd : 2016-09-02
// separated by .
fmt.Println("yyyy.mm.dd : ", current.Format("2006.01.02"))
// yyyy.mm.dd : 2016.09.02
fmt.Println("yyyy-mm-dd HH:mm:ss : ", current.Format("2006-01-02 15:04:05"))
// yyyy-mm-dd HH:mm:ss : 2016-09-02 15:53:07
// StampMicro
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994
//StampNano
fmt.Println("yyyy-mm-dd HH:mm:ss: ", current.Format("2006-01-02 15:04:05.000000000"))
// yyyy-mm-dd HH:mm:ss: 2016-09-02 15:53:07.159994437
}

package main
import (
"fmt"
"time"
)
func main() {
v , _ := time.Now().UTC().MarshalText()
fmt.Println(string(v))
}
Output : 2009-11-10T23:00:00Z
Go Playground

Please find the simple solution to convete Date & Time Format in Go Lang. Please find the example below.
Package Link: https://github.com/vigneshuvi/GoDateFormat.
Please find the plackholders:https://medium.com/#Martynas/formatting-date-and-time-in-golang-5816112bf098
package main
// Import Package
import (
"fmt"
"time"
"github.com/vigneshuvi/GoDateFormat"
)
func main() {
fmt.Println("Go Date Format(Today - 'yyyy-MM-dd HH:mm:ss Z'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MM-dd HH:mm:ss Z")))
fmt.Println("Go Date Format(Today - 'yyyy-MMM-dd'): ", GetToday(GoDateFormat.ConvertFormat("yyyy-MMM-dd")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS")))
fmt.Println("Go Time Format(NOW - 'HH:MM:SS tt'): ", GetToday(GoDateFormat.ConvertFormat("HH:MM:SS tt")))
}
func GetToday(format string) (todayString string){
today := time.Now()
todayString = today.Format(format);
return
}

strconv.Itoa(int(time.Now().Unix()))

Go Playground
http://play.golang.org/p/DN5Py5MxaB
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
// The Time type implements the Stringer interface -- it
// has a String() method which gets called automatically by
// functions like Printf().
fmt.Printf("%s\n", t)
// See the Constants section for more formats
// http://golang.org/pkg/time/#Time.Format
formatedTime := t.Format(time.RFC1123)
fmt.Println(formatedTime)
}

Related

Formatting Go time with Z precision

I have the following Go code:
now := time.Now().UTC().String()
log.Info("time is: " + now)
When this runs it prints out:
time is: 2020-08-21 10:34:43.3547088 +0000 UTC
I only want time precision in HH:mm:ss such that it would print out as:
time is: 2020-08-21 10:34:43Z
What do I need to change to format my time correctly? Must contain that "Z" at the end.
You can use time format to get time as what you want.
func main() {
now := time.Now().UTC().Format("2006-01-02 15:04:05Z")
fmt.Println("time is: " + now)
}
in playground
The format you are trying to print is not from one of the standard formats defined in the time package. Its so close to RFC3339 barring the T notation. But still Format() function allows you to provide a custom format string to show how your time should be printed.
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now().UTC()
fmt.Printf("time is: %v", now.Format("2006-01-02 15:04:05Z"))
//fmt.Println("time is: " + now)
}
now := time.Now().UTC().Format("2006-01-02 15:04:05Z")
log.Info("time is: " + now)
ref: https://dev.to/mahbubzulkarnain/golang-time-format-22j0

What's the format of timestamp to write parquet file in go

I am trying to write a Go struct in a Parquet file and upload to S3. What format and type do I specify for timestamp parameter in the struct so that athena displays correct timestamp when reading from the parquet file.
type example struct {
ID int64 `parquet:"name=id, type=INT64"`
CreatedAt int64 `parquet:"name=created_at,type=TIMESTAMP_MILLIS"`
}
ex := example{}
ex.ID = int64(10)
ex.CreatedAt = time.Now().Unix()
fw, err := ParquetFile.NewLocalFileWriter("new.parquet")
pw, err := ParquetWriter.NewParquetWriter(fw, new(example), 1)
pw.Write(ex)
Upload the file new.parquet to S3
Reference - https://github.com/xitongsys/parquet-go. I created a table in Athena with int and timestamp field for the same and trying querying the table. The date is showing something like - 1970-01-18 21:54:23.751.
which no where matches the current timestamp.
For example,
package main
import (
"fmt"
"time"
)
func main() {
type example struct {
CreatedAt int64 `parquet:"name=created_at,type=TIMESTAMP_MILLIS"`
}
ex := example{}
ex.CreatedAt = time.Now().UnixNano() / int64(time.Millisecond)
fmt.Println(ex.CreatedAt)
}
Playground: https://play.golang.org/p/ePOlUKiT6fD
Output:
1257894000000

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)

Generating Random Timestamps in Go

I'd like to generate a random timestamp within the last relative 3 years and have it be printed out with this format: %d/%b/%Y:%H:%M:%S %z
Here is what I have right now:
package main
import (
"strconv"
"time"
"math/rand"
"fmt"
)
func randomTimestamp() time.Time {
randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000
randomNow, err := time.Parse("10/Oct/2000:13:55:36 -0700", strconv.FormatInt(randomTime, 10))
if err != nil {
panic(err)
}
return randomNow
}
func main() {
fmt.Println(randomTimestamp().String())
}
This always throws: panic: parsing time "...": month out of range. How can I generate a random timestamp for a given range, then convert it to the string format I want with the standard library?
Don't use time.Parse. You have a Unix time, not a time string. Use the Unix() method instead. https://golang.org/pkg/time/#Unix. You can also choose a minimum time value, say 1/1/1900 and add a random Duration of seconds to the time using the Add method on Time and passing a Duration you made with the Ticks() method. https://golang.org/pkg/time/#Duration
Here's a Go Playground link. Just remember that the Go Playground doesn't support actual randomness. https://play.golang.org/p/qYTpnbml_N
package main
import (
"time"
"math/rand"
"fmt"
)
func randomTimestamp() time.Time {
randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000
randomNow := time.Unix(randomTime, 0)
return randomNow
}
func main() {
fmt.Println(randomTimestamp().String())
}

Parsing date/time strings which are not 'standard' formats

How do I parse non-standard date/time strings in Go. In example if I wanted to convert the string 10/15/1983 into a time.Time? The time.Parse() function supposedly allows you to specify a format.
http://play.golang.org/p/v5DbowXt1x
package main
import "fmt"
import "time"
func main() {
test, err := time.Parse("10/15/1983", "10/15/1983")
if err != nil {
panic(err)
}
fmt.Println(test)
}
This results in a panic.
panic: parsing time "10/15/1983" as "10/15/1983": cannot parse "" as "0/"
Logically that makes sense because how is it supposed to know which is the day and which is the month.
Other languages have a function similar to the following:
parse("mm/dd/yyyy", "10/15/1983")
I cannot find such a function in the Go docs, is my only choice to regex?
There are some key values that the time.Parse is looking for.
By changing:
test, err := time.Parse("10/15/1983", "10/15/1983")
to
test, err := time.Parse("01/02/2006", "10/15/1983")
the parser will recognize it.
Here's the modified code on the playground.
package main
import "fmt"
import "time"
func main() {
test, err := time.Parse("01/02/2006", "10/15/1983")
if err != nil {
panic(err)
}
fmt.Println(test)
}
You can utilize the constants list in the src/pkg/time/format.go file to create your own parse formats.
const (
stdLongMonth = "January"
stdMonth = "Jan"
stdNumMonth = "1"
stdZeroMonth = "01"
stdLongWeekDay = "Monday"
stdWeekDay = "Mon"
stdDay = "2"
stdUnderDay = "_2"
stdZeroDay = "02"
stdHour = "15"
stdHour12 = "3"
stdZeroHour12 = "03"
stdMinute = "4"
stdZeroMinute = "04"
stdSecond = "5"
stdZeroSecond = "05"
stdLongYear = "2006"
stdYear = "06"
stdPM = "PM"
stdpm = "pm"
stdTZ = "MST"
stdISO8601TZ = "Z0700" // prints Z for UTC
stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
stdNumTZ = "-0700" // always numeric
stdNumShortTZ = "-07" // always numeric
stdNumColonTZ = "-07:00" // always numeric
)
So anytime your format specifies a year, it should be done with "06" or "2006", seconds are specified by "05" or "5" and time zones are specified at "MST", "Z0700", "Z07:00", "-0700", "-07" or "-07:00". If you reference the constants list you can likely put together any standard format you'd need to parse.
For example, if you want to parse the date/time in the Common Log Format, the format Apache uses for its log files, you would do so by passing the following string to time.Parse() as the layout argument.
"02/Jan/2006:15:04:05 -0700"
"02" denotes the day of the month field, "Jan" denotes the month name field, "2006" denotes the year field, "15" denotes the hour of day field in 24 hour format, "04" denotes the minutes field, "05" denotes the seconds field and "-0700" denotes the time zone field.
That format would parse the current PST time: 31/Dec/2012:15:32:25 -0800
So the time.Parse() call would look like this:
test, err := time.Parse("02/Jan/2006:15:04:05 -0700", "31/Dec/2012:15:32:25 -0800")
If you can't remember the Numbers in the specifying layout ("2006-01-02T15:04:05.000Z"), you may use my simple date formatting library github.com/metakeule/fmtdate that uses MS Excel conventions, like Y,M,D,h and internally translates them to the number format:
package main
import (
"github.com/metakeule/fmtdate"
"fmt"
)
func main() {
test, err := fmtdate.Parse("MM/DD/YYYY", "10/15/1983")
if err != nil {
panic(err)
}
fmt.Println(test)
}
If you are looking for a C-Style formatting function: After reviewing some of the options I have chosen https://github.com/cactus/gostrftime as it generally follows the strfmt(3) notation.
To quote the example:
import (
"fmt"
"time"
"github.com/cactus/gostrftime"
)
func main() {
now := time.Now()
fmt.Println(gostrftime.Format("%Y-%m-%d", now))
}
If a date format has to be used by both C and Go and the C implementation is not to be touched there's no choice but to adapt on the Go end. The above package fulfills that need.
If you don't want bother remembering the magic numbers, you can do this:
package main
import (
"fmt"
"time"
)
func main() {
var (
y, d int
m time.Month
)
fmt.Sscanf("10/15/1983", "%v/%v/%v", &m, &d, &y)
t := time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
fmt.Println(t) // 1983-10-15 00:00:00 +0000 UTC
}
https://golang.org/pkg/fmt#Sscanf

Resources