Python 时间戳/字符串/时间 转换

概要
平时对于时间的处理经常使用python的time和datetime模块,但是用来多次还是对其中的时间戳,字符串和时间转换应用的不太熟练,时间长了不使用就理不清楚,为此整理成文。

视图
时间戳,时间,字符串之间的关系整理如下图:

 


示例
时间戳和时间的转换
import time


if __name__ == "__main__":
# 时间戳: time.time() 返回当前时间戳
seconds = time.time()

# time.localtime()将时间戳转换为struct_time
s_time = time.localtime(seconds)
print s_time

# time.mktime()将struct_time转换为时间戳
print time.mktime(s_time)
1
2
3
4
5
6
7
8
9
10
11
12
13
# 输出 struct time: 包含年,月,日,小时,分钟,秒等
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=11, tm_hour=17, tm_min=31, tm_sec=57, tm_wday=5, tm_yday=223, tm_isdst=0)

# 时间戳
1533980060.0
1
2
3
4
5
时间和字符串之间的转换
import time


if __name__ == "__main__":
# time.strptime() 将字符串转换为struct_time
# %Y: 年
# %m: 月
# %d: 日
# %H: 时, %M:分, %S:秒, 更多详细需参考python time模块文档
s_time = time.strptime("2018-08-07", "%Y-%m-%d")
print s_time

# time.strftime()将struct_time转换为字符串
print time.strftime("%Y-%m-%d %H:%M:%S", s_time)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 输出
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=7, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=219, tm_isdst=-1)

2018-08-07 00:00:00
1
2
3
4
时间戳和字符串之间的转换

时间戳和字符串之间没有直接的转换方法,需要借助struct_time实现转换

import time


if __name__ == "__main__":
# 时间戳
seconds = time.time()

# 时间戳转换为字符串
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))

# 字符串转换为时间戳
print time.mktime(time.strptime("2018-08-07", "%Y-%m-%d"))
1
2
3
4
5
6
7
8
9
10
11
12
# 输出
2018-08-11 17:47:43

1533571200.0
---------------------
作者:回眸郎
来源:CSDN
原文:https://blog.csdn.net/ymaini/article/details/81589157
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自www.cnblogs.com/linwenbin/p/10905341.html