python3将时间戳转为日期,将日期转为时间戳 – Python3教程

上一章Python教程请查看:python3获取当前时间

在本文中,你将学习如何将时间戳转换为datetime对象,将datetime对象转换为时间戳(通过示例)。

将日期和时间作为时间戳存储在数据库中是很常见的,Unix时间戳是特定日期到UTC的1970年1月1日之间的秒数。

示例1:Python时间戳转为datetime

from datetime import datetime
timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

这里,我们从datetime模块导入了datetime类。然后,我们使用datetime.fromtimestamp()类方法,它返回本地日期和时间(datetime对象),该对象存储在dt_object变量中。

注意:可以使用strftime()方法轻松地从datetime对象创建表示日期和时间的字符串。

例2:Python
datetime 转为时间戳timestamp

可以使用datetime.timestamp()方法从datetime对象获取时间戳。

from datetime import datetime
# 当前 date and time
now = datetime.now()
timestamp = datetime.timestamp(now)
print("timestamp =", timestamp)

来源:

https://www.srcmini02.com/2649.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_35757.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?