參考鏈接: Python | 輸出格式化 output format
本文翻譯自:How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]
? This question already has an answer here: 這個(gè)問(wèn)題已經(jīng)在這里有了答案:??
? How do I parse an ISO 8601-formatted date? 如何解析ISO 8601格式的日期舀奶? 26 answers 26個(gè)答案?
?I'm getting a datetime string in a format like "2009-05-28T16:15:00" (this is ISO 8601, I believe). 我正在以類似“ 2009-05-28T16:15:00”的格式獲取日期時(shí)間字符串(我相信這是ISO 8601)蔚叨。 One hackish option seems to be to parse the string using time.strptime and passing the first six elements of the tuple into the datetime constructor, like: 一種可能的選擇似乎是使用time.strptime解析字符串敬扛,并將元組的前六個(gè)元素傳遞到datetime構(gòu)造函數(shù)中繁扎,例如:??
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
?I haven't been able to find a "cleaner" way of doing this. 我還沒有找到一種“清潔”的方法幔荒。 Is there one? 有一個(gè)嗎??
#1樓
參考:https://stackoom.com/question/449d/如何將ISO-日期時(shí)間字符串轉(zhuǎn)換為Python日期時(shí)間對(duì)象-重復(fù)
#2樓
import datetime, time
def convert_enddate_to_seconds(self, ts):
? ? """Takes ISO 8601 format(string) and converts into epoch time."""
? ? dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+\
? ? ? ? ? ? ? ? datetime.timedelta(hours=int(ts[-5:-3]),
? ? ? ? ? ? ? ? minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
? ? seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
? ? return seconds
?This also includes the milliseconds and time zone. 這還包括毫秒和時(shí)區(qū)梳玫。??
?If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time. 如果時(shí)間是“ 2012-09-30T15:31:50.262-08:00”爹梁,則它將轉(zhuǎn)換為紀(jì)元時(shí)間。??
>>> import datetime, time
>>> ts = '2012-09-30T15:31:50.262-08:00'
>>> dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')+ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
>>> seconds = time.mktime(dt.timetuple()) + dt.microsecond/1000000.0
>>> seconds
1348990310.26
#3樓
?Arrow looks promising for this: Arrow對(duì)此很有希望:??
>>> import arrow
>>> arrow.get('2014-11-13T14:53:18.694072+00:00').datetime
datetime.datetime(2014, 11, 13, 14, 53, 18, 694072, tzinfo=tzoffset(None, 0))
? Arrow is a Python library that provides a sensible, intelligent way of creating, manipulating, formatting and converting dates and times. Arrow是一個(gè)Python庫(kù)提澎,它提供了一種明智姚垃,智能的方式來(lái)創(chuàng)建,操作盼忌,格式化和轉(zhuǎn)換日期和時(shí)間积糯。 Arrow is simple, lightweight and heavily inspired by moment.js and requests . Arrow很簡(jiǎn)單,輕巧谦纱,并且受moment.js和request的啟發(fā)很大 看成。??
#4樓
?You should keep an eye on the timezone information, as you might get into trouble when comparing non-tz-aware datetimes with tz-aware ones. 您應(yīng)該注意時(shí)區(qū)信息,因?yàn)樵诒容^非tz感知的日期時(shí)間和tz感知的日期時(shí)間時(shí)可能會(huì)遇到麻煩跨嘉。??
?It's probably the best to always make them tz-aware (even if only as UTC), unless you really know why it wouldn't be of any use to do so. 最好始終使它們具有tz意識(shí)(即使僅作為UTC)川慌,除非您真的知道為什么這樣做沒有任何用處。??
#-----------------------------------------------
import datetime
import pytz
import dateutil.parser
#-----------------------------------------------
utc = pytz.utc
BERLIN = pytz.timezone('Europe/Berlin')
#-----------------------------------------------
def to_iso8601(when=None, tz=BERLIN):
? if not when:
? ? when = datetime.datetime.now(tz)
? if not when.tzinfo:
? ? when = tz.localize(when)
? _when = when.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
? return _when[:-8] + _when[-5:] # Remove microseconds
#-----------------------------------------------
def from_iso8601(when=None, tz=BERLIN):
? _when = dateutil.parser.parse(when)
? if not _when.tzinfo:
? ? _when = tz.localize(_when)
? return _when
#-----------------------------------------------
#5樓
?aniso8601 should handle this. aniso8601應(yīng)該處理這個(gè)問(wèn)題祠乃。 It also understands timezones, Python 2 and Python 3, and it has a reasonable coverage of the rest of ISO 8601 , should you ever need it. 它還了解時(shí)區(qū)梦重,Python 2和Python 3,并且在需要時(shí)可以合理涵蓋ISO 8601的其余部分跳纳。??
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
#6樓
?Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm] . 由于ISO 8601允許存在許多可選的冒號(hào)和破折號(hào)忍饰,因此基本上CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm] 。 If you want to use strptime, you need to strip out those variations first. 如果要使用strptime寺庄,則需要先刪除這些變化艾蓝。??
?The goal is to generate a UTC datetime object. 目標(biāo)是生成UTC日期時(shí)間對(duì)象力崇。??
?If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z : 如果您只想使用帶有Z后綴的UTC的基本情況,例如2016-06-29T19:36:29.3453Z :??
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
?If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. 如果要處理時(shí)區(qū)偏移赢织,例如2016-06-29T19:36:29.3453-0400或2008-09-03T20:56:35.450686+05:00使用以下內(nèi)容亮靴。 These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse. 這些會(huì)將所有變體轉(zhuǎn)換成沒有變量定界符的內(nèi)容,例如20080903T205635.450686+0500 于置,使其更一致/更容易解析茧吊。??
import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )
?If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' ) then you need to manually offset the time from Z (UTC). 如果您的系統(tǒng)不支持%z strptime指令(您會(huì)看到類似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' ),則需要手動(dòng)從Z (UTC)偏移時(shí)間八毯。 Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (ie, Jython , Cython , etc.). 注意%z可能在版本低于3的Python版本中無(wú)法在您的系統(tǒng)上運(yùn)行搓侄,因?yàn)樗Q于C庫(kù)支持,該支持因系統(tǒng)/ Python構(gòu)建類型(即Jython 话速, Cython等)而異讶踪。??
import re
import datetime
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"[+|-]",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
? ? sign = split_timestamp[1]
? ? offset = split_timestamp[2]
else:
? ? sign = None
? ? offset = None
# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
? ? # Create timedelta based on offset
? ? offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))
? ? # Offset datetime with timedelta
? ? output_datetime = output_datetime + offset_delta