Python3将时间戳转换为指定格式日期

川长思鸟来 2023-01-18 06:43 225阅读 0赞

Python 将时间戳转换为指定格式日期

给定一个时间戳,将其转换为指定格式的时间。

注意时区的设置

当前时间

  1. import time
  2. # 获得当前时间时间戳
  3. now = int(time.time())
  4. #转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
  5. timeArray = time.localtime(now)
  6. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  7. print(otherStyleTime)

执行以上代码输出结果为:

2019-05-21 18:02:49

  1. import datetime
  2. # 获得当前时间
  3. now = datetime.datetime.now()
  4. # 转换为指定的格式
  5. otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
  6. print(otherStyleTime)

执行以上代码输出结果为:

2019-05-21 18:03:48

指定时间戳

  1. import time
  2. timeStamp = 1557502800
  3. timeArray = time.localtime(timeStamp)
  4. otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
  5. print(otherStyleTime)

执行以上代码输出结果为:

2019-05-10 23:40:00

  1. import datetime
  2. timeStamp = 1557502800
  3. dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
  4. otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
  5. print(otherStyleTime)

执行以上代码输出结果为:

2019-05-10 23:40:00

发表评论

表情:
评论列表 (有 0 条评论,225人围观)

还没有评论,来说两句吧...

相关阅读

    相关 日期转换时间

    日期格式比较多,也比较复杂,全部实现转换有些麻烦,而且还是费力不讨好,所以就以最常用的时间格式来转换。 //日期转时间戳 function transdate