Question

I want to get a datetime, counting weeks from a date, days from a week and seconds from 00:00 time.

With Python I can use this:

BASE_TIME = datetime.datetime(1980,1,6,0,0)
tdelta = datetime.timedelta(weeks = 1722,
                            days = 1,
                            seconds = 66355)
mydate = BASE_DATE + tdelta

I'm trying to get it with Go, but I have some problems to reach it:

package main

import (
    "fmt"
    "time"
)

var base = time.Date(1980, 1, 6, 0, 0, 0, 0, time.UTC)

func main() {
    weeks := 1722
    days := 1
    seconds := 66355
    weeksToSecs := 7 * 24 * 60 * 60
    daysToSecs := 24 * 60 * 60
    totalSecs := (weeks * weeksToSecs) + (days * daysToSecs) + seconds
    nanosecs := int64(totalSecs) * 1000000000

    //delta := time.Date(0, 0, 0, 0, 0, totalSecs, 0, time.UTC)

    date := base.Add(nanosecs)

    fmt.Printf("Result: %s", date)

}

prog.go:21: cannot use nanosecs (type int64) as type time.Duration in function argument

http://play.golang.org/p/XWSK_QaXrQ

What I'm missing?
Thanks

Was it helpful?

Solution

package main

import (
        "fmt"
        "time"
)

func main() {
        baseTime := time.Date(1980, 1, 6, 0, 0, 0, 0, time.UTC)
        date := baseTime.Add(1722*7*24*time.Hour + 24*time.Hour + 66355*time.Second)
        fmt.Println(date)
}

Playground


Output

2013-01-07 18:25:55 +0000 UTC

OTHER TIPS

jnml's answer works and is more idiomatic go. But to illustrate why your original code didn't work, all you have to do is change one line.

date := base.Add(time.Duration(nanosecs)) will cast the nanosecs to a time.Duration which is the type that Add expects as opposed to int64. Go will not automatically cast a type for you so it complained about the type being int64.

timeutil supports timedelta and strftime.

package main

import (
    "fmt"
    "time"

    "github.com/leekchan/timeutil"
)

func main() {
    base := time.Date(2015, 2, 3, 0, 0, 0, 0, time.UTC)
    td := timeutil.Timedelta{Days: 10, Minutes: 17, Seconds: 56}

    result := base.Add(td.Duration())
    fmt.Println(result) // "2015-02-13 00:17:56 +0000 UTC"
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top