Python時間、日期、時間戳之間的轉換

1、字符串與爲時間字符串之間的互相轉換python

  方法:time模塊下的strptime方法數組

a = "2012-11-11 23:40:00"
# 字符串轉換爲時間字符串
import time
timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")

# 時間字符串轉換爲字符串
b = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(type(b))# <class 'str'>

 

2、將字符串的時間轉換爲時間戳spa

  方法:字符串 --> 時間字符串 --> 時間戳code

 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

 

3、獲得時間戳(10位和13位)orm

import time
t = time.time()
print(t) # 1436428326.207596
t_10 = int(t)# 10位時間戳
t_13 = int(round(time.time() * 1000))# 13位時間戳
print(t_10)# 1436428326
print(t_13)# 1436428326207

 

4、將時間戳轉換爲時間格式的字符串blog

  方法一:利用localtime()轉換爲時間數組,而後格式化爲須要的格式three

timeStamp = 1381419600# 10位時間戳
# timeStamp_13 = 1381419600234# 13位時間戳
timeArray = time.localtime(timeStamp)# timeStamp_13 / 1000
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(otherStyletime)# "2013-10-10 23:40:00"(str)

  方法2、利用datetime模塊下的utcfromtimestamp方法字符串

import datetime
timeStamp = 1381419600
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
otherStyleTime = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyletime) # "2013-10-10 23:40:00"

 

5、時間字符串轉換爲時間戳it

  方法:利用time模塊的mktime方法io

import time
import datetime
# 先得到時間數組格式的日期
test_date = datetime.datetime.now()
# 轉換爲時間戳:
timeStamp = int(time.mktime(test_date.timetuple()))

 

6、時間字符串加減日期

  方法:利用datetime模塊下的timedelta方法

import time
import datetime
# 先得到時間數組格式的日期
test_datetime = datetime.datetime.now()
threeDayAgo = (test_datetime - datetime.timedelta(days = 3))# 3天前
# 注:timedelta()的參數有:days,hours,seconds,microseconds

 

7、獲取 UTC 時間戳

import calendar 
calendar.timegm(datetime.datetime.utcnow().timetuple())

 

 

8、python 格式化時間含中文報錯 UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence'

import time
print(time.strftime(u'%Y年%m月%d日',time.localtime(time.time())))

# 執行上面代碼會報錯  UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: Illegal byte sequence


# 解決方式:
time.strftime('%Y{y}%m{m}%d{d}').format(y='',m='',d='')
相關文章
相關標籤/搜索