推荐
关注
TOP
Message

Python / Golang 时间与时间戳之间的相互转化

何为时间戳:

时间戳是使用数字签名技术产生的数据,签名的对象包括了原始文件信息、签名参数、签名时间等信息。时间戳系统用来产生和管理时间戳,对签名对象进行数字签名产生时间戳,以证明原始文件在签名时间之前已经存在。

时间戳格式种类:

  • 10位数的时间戳是以 秒 为单位,如:1530027865
  • 13位数的时间戳是以 毫秒 为单位, 如:1530027865231
  • 19位数的时间戳是以 纳秒 为单位,如:1530027865231834600

golang 代码

/*
@Time : 2022/11/8 14:52
@Author : zic
@File : time
@Software: GoLand
@blog : https://www.cnblogs.com/zichliang
*/
package main

import (
	"fmt"
	"strconv"
	"time"
)

func main() {
	//获取当前时间 并格式化
	t := time.Now()
	fmt.Println(t.Format("2006-01-02 15:04:05"))

	//获取当前时间戳
	t = time.Now()
	fmt.Println(t.Unix()) //1531293019

	//时间戳转换为时间
	tm := time.Unix(1667889978, 0)
	fmt.Println(tm.Format("2006-01-02 15:04:05"))

	//时间转换为时间戳
	timeUnix, _ := time.Parse("2006-01-02 15:04:05", "2022-11-08 14:46:18")
	fmt.Println(timeUnix.Unix())

	// 13位时间戳转换成时间
	data, _ := strconv.ParseInt(strconv.Itoa(1667888972000), 10, 64)
	nowTime := time.Unix(data/1000, 0).Format("2006-01-02 15:04:05")
	fmt.Println(nowTime) //2022-11-08 14:29:32

	// (标准时间 2022-11-08 14:29:32 )时间转13位时间戳
	timeUnix, _ = time.Parse("2006-01-02 15:04:05", nowTime)
	fmt.Println(timeUnix.UnixNano() / 1e6) // 1667917772000

	// 非标准时间 转13位时间戳
	formatTime := "2022-11-08"
	ft, _ := time.Parse("2006-01-02", formatTime)
	fmt.Println((ft.UTC().Unix() - 8*3600) * 1000) // 10位就不用乘1000 其实感觉有更好的方法 ....

}

python代码

# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 #
# @Time    : 2022/11/1 10:34
# @Author  : zicliang
# @Email   : hybpjx@163.com
# @blog    : https://www.cnblogs.com/zichliang
# @File    : __init__.py.py
# @Software: PyCharm

import re
import time


# 时间转换为时间戳
def time_stamp(time_str):
    s_t = time.strptime(time_str, "%Y-%m-%d %H:%M:%S")
    return int(time.mktime(s_t))


# 仅支持 Js 时间戳
def time_format(time_num: int):
    import time
    timeStamp = int(time_num) / 1000
    timeArray = time.localtime(timeStamp)
    otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)

    return otherStyleTime


#  自己写的校验时间类
def verify_date(date):
    # 如果得到的值是整形 代表是时间戳
    if str(date).startswith("16"):
        if len(str(date)) == 13:
            timeStamp = int(date) / 1000
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
            title_date = otherStyleTime
        elif len(str(date)) == 10:
            timeStamp = int(date)
            timeArray = time.localtime(timeStamp)
            otherStyleTime = time.strftime("%Y-%m-%d", timeArray)
            title_date = otherStyleTime
        else:
            return "传入时间错误"
    else:
        # 不是的话 就直接传入时间
        try:
            title_date = re.findall(r'(20\d{2}[^\d]\d{1,2}[^\d]\d{1,2})', date)[0]
        except IndexError:
            title_date = date
    return title_date

posted @ 2022-11-08 14:54  始識  阅读(175)  评论(0编辑  收藏  举报