python中的時間轉換,秒級時間戳轉string,string轉時間

木头左發表於2024-04-20

import time
import datetime


def paserTime(timestamp):
    t = time.time()
    f=time.localtime(timestamp/1000)
    print (t)                       #原始時間資料
    # print (int(t))                  #秒級時間戳
    print (int(round(t * 1000)))    #毫秒級時間戳

    #nowTime = lambda: int(round(t * 1000))
  #  print(nowTime());  # 毫秒級時間戳,基於lambda
    nowTime = lambda:timestamp
    str=time.strftime('%Y-%m-%d %H:%M:%S',f)
    print(str)  # 日期格式化

    return str
# paserTime(time.time())
def now():
    nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 現在
    print(nowTime)
def nowTime():
    t = time.time()
    f = time.localtime(int(t))
    # print(t)
    str = time.strftime('%Y-%m-%d %H:%M:%S', f)
    print(str)  # 日期格式化
    return str
# nowTime()
def long2Str(longTime):
    f = time.localtime(int(longTime))
    # print(t)
    str = time.strftime('%Y-%m-%d %H:%M:%S', f)
    print(str)  # 日期格式化
    return str
def str2time(str):
    date_time = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    # print(date_time)
    return date_time

def str2timestamp(str):
    timstamp=time.mktime(time.strptime(str, '%Y-%m-%d %H:%M:%S'))
    # print(timstamp)
    return timstamp
    # time.mktime()   與    time.localtime() 互為還原函式。
    # time.mktime(timetuple) :將時間元組轉換成時間戳
    # time.localtime([timestamp]):將時間戳轉會為時間元組
# print(str2timestamp(str2)-str2timestamp(str))```


 


![](https://mutouzuo.oss-cn-hangzhou.aliyuncs.com/my/mudouzuo1.png)

相關文章