GolangNote

Golang笔记

GoLang 实现python timedelta 函数功能

Permalink

在python 里有个函数datetime.timedelta 很有用,用来计算某个时间往后多少时间后的时间。

有点拗口,看看python 示例:

Python: timedelta
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from datetime import datetime,timedelta

now = datetime.now()

yestoday = now - timedelta(days=1)
tommorow = now + timedelta(days=1)

next_year = now + timedelta(days = 365)

golang 实现起来就不那么简洁了:

Go: timedelta
1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
    "fmt"
    "time"
)

func main() {
    baseTime := time.Date(2015, 10, 25, 0, 0, 0, 0, time.UTC)
    // after 2 days 8 hour 100 second
    date := baseTime.Add(2*24*time.Hour + 8*time.Hour + 100*time.Second)
    fmt.Println(date)
}

本文网址: https://golangnote.com/topic/91.html 转摘请注明来源

Related articles

Write a Comment to "GoLang 实现python timedelta 函数功能"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 15ms