前言
大家都知道,Python自帶的datetime庫提供了將datetime轉(zhuǎn)為ISO 8610格式的函數(shù),但是對于時間間隔(inteval)并沒有提供轉(zhuǎn)換的函數(shù),下面我們動手寫一個。 下面話不多說了,來一起看看詳細(xì)的介紹吧。
對于時間間隔,ISO 8601的表示形式如下:

P表示的是時間間隔的前綴。YMDHMS分別表示年月日時分秒,W表示周。T表示后面的字符是精確到天的,也就是以小時表示開始的前綴。
英文解釋如下 :
[P] is used as time-interval (period) designator, preceding a data element which represents a given duration of a time-interval;
The character [T] shall be used as time designator to indicate the start of the representation of time of the day in date and time expressions.
下面是實(shí)現(xiàn)代碼:
# -*- encoding: utf-8 -*-import datetimedef isoformat(time): ''' 將datetime或者timedelta對象轉(zhuǎn)換成ISO 8601時間標(biāo)準(zhǔn)格式字符串 :param time: 給定datetime或者timedelta :return: 根據(jù)ISO 8601時間標(biāo)準(zhǔn)格式進(jìn)行輸出 ''' if isinstance(time, datetime.datetime): # 如果輸入是datetime return time.isoformat(); elif isinstance(time, datetime.timedelta): # 如果輸入時timedelta,計(jì)算其代表的時分秒 hours = time.seconds // 3600 minutes = time.seconds % 3600 // 60 seconds = time.seconds % 3600 % 60 return 'P%sDT%sH%sM%sS' % (time.days, hours, minutes, seconds) # 將字符串進(jìn)行連接if __name__ == '__main__': dtnow = datetime.datetime.now() # 獲取現(xiàn)在時間 print(isoformat(dtnow)) dtpast = datetime.datetime(1990, 12, 31) # 獲取過去某個時間點(diǎn) print(isoformat(dtpast)) interval = dtnow - dtpast # 得到時間差 print(interval) print(isoformat(interval))
輸出結(jié)果如下:
2017-01-14T10:54:28.3230001990-12-31T00:00:009511 days, 10:54:28.323000P9511DT10H54M28S
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選