[轉(zhuǎn)載] 如何將ISO 8601日期時(shí)間字符串轉(zhuǎn)換為Python日期時(shí)間對(duì)象呻逆? [重復(fù)]

參考鏈接: 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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市泊交,隨后出現(xiàn)的幾起案子乳讥,更是在濱河造成了極大的恐慌,老刑警劉巖廓俭,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件云石,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡研乒,警方通過(guò)查閱死者的電腦和手機(jī)汹忠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門葫笼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)爱葵,“玉大人,你說(shuō)我怎么就攤上這事吧趣¢匣#” “怎么了赋焕?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)仰楚。 經(jīng)常有香客問(wèn)我隆判,道長(zhǎng),這世上最難降的妖魔是什么僧界? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任侨嘀,我火速辦了婚禮,結(jié)果婚禮上捂襟,老公的妹妹穿的比我還像新娘咬腕。我一直安慰自己,他們只是感情好葬荷,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布涨共。 她就那樣靜靜地躺著纽帖,像睡著了一般。 火紅的嫁衣襯著肌膚如雪举反。 梳的紋絲不亂的頭發(fā)上懊直,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音火鼻,去河邊找鬼室囊。 笑死,一個(gè)胖子當(dāng)著我的面吹牛魁索,可吹牛的內(nèi)容都是我干的融撞。 我是一名探鬼主播,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼蛾默,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼懦铺!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起支鸡,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎趁窃,沒想到半個(gè)月后牧挣,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡醒陆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年瀑构,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片刨摩。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡寺晌,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出澡刹,到底是詐尸還是另有隱情呻征,我是刑警寧澤,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布罢浇,位于F島的核電站陆赋,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏嚷闭。R本人自食惡果不足惜攒岛,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望胞锰。 院中可真熱鬧灾锯,春花似錦、人聲如沸嗅榕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至领突,卻和暖如春暖璧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背君旦。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來(lái)泰國(guó)打工澎办, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人金砍。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓局蚀,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親恕稠。 傳聞我的和親對(duì)象是個(gè)殘疾皇子琅绅,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容