python中时间字符串与时间戳的相互转换

:时间字符串转换为时间戳

[Python] 纯文本查看 复制代码
1
2
3
4
5
6
7
8
#  时间字符串转换为时间戳
a= "2013-10-10 23:40:00"
# 将其转换为时间数组
import time
timeArray= time.strptime(a,"%Y-%m-%d %H:%M:%S")
# 转换为时间戳:
timeStamp= int(time.mktime(timeArray))
print(timeStamp) # 1381419600



二:时间戳转换为时间字符串

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
# 将时间戳转换成时间字符串
# 方法一:
# 利用localtime()
# 转换为时间数组, 然后格式化为需要的格式, 如
timeStamp= 1381419600
timeArray= time.localtime(timeStamp)
otherStyleTime= time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyleTime)   # otherStyletime == "2013-10-10 23:40:00"
 
# 方法二:
import datetime
timeStamp= 1381419600
dateArray= datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime= dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)   # otherStyletime == "2013-10-10 23:40:00"



三:获取当前时间并转换为指定日期格式

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
# 获取当前时间并转换为指定日期格式
# 方法一:
import time
# 获得当前时间时间戳
now= int(time.time())#  ->这是时间戳
# 转换为其他日期格式, 如: "%Y-%m-%d %H:%M:%S"
timeArray= time.localtime(timeStamp)
otherStyleTime= time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
 
# 方法二:
import datetime
# 获得当前时间
now= datetime.datetime.now() # ->这是时间数组格式
# 转换为指定的格式:
otherStyleTime= now.strftime("%Y-%m-%d %H:%M:%S")



扩展:

[Python] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
'''
%a 星期的简写。如 星期三为Web
%A 星期的全写。如 星期三为Wednesday
%b 月份的简写。如4月份为Apr
%B 月份的全写。如4月份为April
%c:  日期时间的字符串表示。(如: 04/07/10 10:43:39)
%d:  日在这个月中的天数(是这个月的第几天)
%f:  微秒(范围[0,999999])
%H:  小时(24小时制,[0, 23])
%I:  小时(12小时制,[0, 11])
%j:  日在年中的天数 [001,366](是当年的第几天)
%m:  月份([01,12])
%M:  分钟([00,59])
%p:  AM或者PM
%S:  秒(范围为[00,61],为什么不是[00, 59],参考python手册~_~)
%U:  周在当年的周数当年的第几周),星期天作为周的第一天
%w:  今天在这周的天数,范围为[0, 6],6表示星期天
%W:  周在当年的周数(是当年的第几周),星期一作为周的第一天
%x:  日期字符串(如:04/07/10)
%X:  时间字符串(如:10:43:39)
%y:  2个数字表示的年份
%Y:  4个数字表示的年份
%z:  与utc时间的间隔 (如果是本地时间,返回空字符串)
%Z:  时区名称(如果是本地时间,返回空字符串)
%%:  %% => %
'''



转自博客---https://blog.csdn.net/qq_37193537/article/details/78987949