英文:
How to convert YYYY-MM-DD string format to timestamp in Golang?
问题
抱歉,如果这是一个琐碎的问题。这是我目前的代码。
snapshot = "2017-07-25"
snapshotFilter := " AND cdate = %s"
snapshot, err := time.Parse(time.RFC3339, snapshot)
if err != nil {
log.Fatal(err)
}
queryFilter = queryFilter + fmt.Sprintf(snapshotFilter, pq.FormatTimestamp(snapshot))
这是输出结果:
2017/09/12 09:59:34 parsing time "2017-07-25" as "2006-01-02T15:04:05Z07:": cannot parse "" as "T".
我试图以正确的格式获取 snapshot
,以便将其插入到 PostgreSQL 查询中。
我正在使用以下包:
"database/sql"
"time"
"github.com/gorilla/mux"
"github.com/lib/pq"
编辑:似乎这更多是与 PostgreSQL 有关的问题,只需要将 2017-07-25
用引号括起来并放在 PostgreSQL 查询字符串中即可。
英文:
I'm sorry if this is a trivial question. This is currently what I have.
snapshot = "2017-07-25"
snapshotFilter := " AND cdate = %s"
snapshot, err := time.Parse(time.RFC3339, snapshot)
if err != nil {
log.Fatal(err)
}
queryFilter = queryFilter + fmt.Sprintf(snapshotFilter, pq.FormatTimestamp(snapshot))
This is the output
2017/09/12 09:59:34 parsing time "2017-07-25" as "2006-01-02T15:04:05Z07:": cannot parse "" as "T".
I'm trying to get snapshot
in the correct format to insert it into a postgres query.
I'm using the
"database/sql"
"time"
"github.com/gorilla/mux"
"github.com/lib/pq"
EDIT: is seemed that this was more of an issue with postgres and the 2017-07-25
just needed to be in quotes and put inside the postgres query string.
答案1
得分: 3
如已建议,请使用以下代码:
package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func main() {
snapshot := "2017-07-25"
t, err := time.Parse(layout, snapshot)
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
}
如您在time包的常量文档中所见,有一个参考日期:
Layout = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
它用于指定日期/时间字符串的布局。因此,您提供一个字符串,其中每个3
的出现都会被替换为您指定时间点的12小时制上午/下午表示的小时,每个15
的出现都会被替换为24小时制表示的小时,例如。
有关此方法的所有细节和问题都在文档中的示例代码中有详细解释。
英文:
As already suggested, use this:
package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func main() {
snapshot := "2017-07-25"
t, err := time.Parse(layout, snapshot)
if err != nil {
log.Fatal(err)
}
fmt.Println(t)
}
As you can see in the documentation of constants for the time package there is a reference date
Layout = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
which is used to specify date/time strings layout. So you provide a string and every occurrence of 3
gets replaced by the hour in 12h am/pm notation of your point in time and every occurrence of 15
gets replaced by the hour in 24h representation for example.
All the wrinkles and problems of such an approach are explained in some sample code in the documentation.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论