Python3日期与时间戳转换的几种方法

栏目: Python · 发布时间: 5年前

内容简介:日期和时间的相互转换可以利用Python内置模块我们可以利用内置模块转换结果:

日期和时间的相互转换可以利用 Python 内置模块 timedatetime 完成,且有多种方法供我们选择,当然转换时我们可以直接利用当前时间或指定的字符串格式的时间格式。

获取当前时间转换

我们可以利用内置模块 datetime 获取当前时间,然后将其转换为对应的时间戳。

import datetime
import time
# 获取当前时间
dtime = datetime.datetime.now()
un_time = time.mktime(dtime.timetuple())
print(un_time)
# 将unix时间戳转换为“当前时间”格式
times = datetime.datetime.fromtimestamp(un_time)
print(times)
复制代码

转换结果:

1559568302.0
2019-06-03 21:25:02
复制代码

字符串时间的转换

当然我们也可以直接将字符串类型的时间对应的时间戳。

import datetime
import time

# 字符类型的时间
tss1 = '2019-06-03 21:19:03'
# 转为时间数组
timeArray = time.strptime(tss1, "%Y-%m-%d %H:%M:%S")
print(timeArray)
# timeArray可以调用tm_year等
print(timeArray.tm_year)  # 2019
# 转为时间戳
timeStamp = int(time.mktime(timeArray))
print(timeStamp)  # 1559567943
复制代码

示例结果:

time.struct_time(tm_year=2019, tm_mon=6, tm_mday=3, tm_hour=21, tm_min=19, tm_sec=3, tm_wday=0, tm_yday=154, tm_isdst=-1)
2019
1559567943
复制代码

时间戳转日期的其他方法

localtime

我们可以利用localtime()转换为时间数组,然后格式化为需要的格式

import time
timeStamp = 1559567943
timeArray = time.localtime(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
复制代码

示例结果:

2019-06-03 21:19:03
复制代码

utcfromtimestamp

import time
import datetime
timeStamp = 1559567943
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)
复制代码

以上所述就是小编给大家介绍的《Python3日期与时间戳转换的几种方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Letting Go of the Words

Letting Go of the Words

Janice (Ginny) Redish / Morgan Kaufmann / 2007-06-11 / USD 49.95

"Redish has done her homework and created a thorough overview of the issues in writing for the Web. Ironically, I must recommend that you read her every word so that you can find out why your customer......一起来看看 《Letting Go of the Words》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具