22

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

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
chespinoza
  • 2,638
  • 1
  • 23
  • 46

3 Answers3

23
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
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • How I should pass the weeks like a var to Add? if I pass a int64(weeks) compiler says prog.go:12: invalid operation: int64(weeks) * 7 * 24 * time.Hour (mismatched types int64 and time.Duration)http://play.golang.org/p/P1Dw258gRW – chespinoza Jul 13 '13 at 16:41
  • 3
    Replace `int64(weeks)` with `time.Duration(weeks)` – Stephen Weinberg Jul 13 '13 at 16:59
5

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.

Jeremy Wall
  • 23,907
  • 5
  • 55
  • 73
2

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"
}