[轉載] 如何將ISO 8601日期時間字符串轉換為Python日期時間對象? [重復]

參考鏈接: 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: 這個問題已經在這里有了答案:??

? How do I parse an ISO 8601-formatted date? 如何解析ISO 8601格式的日期? 26 answers 26個答案?


?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”的格式獲取日期時間字符串(我相信這是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解析字符串,并將元組的前六個元素傳遞到datetime構造函數中,例如:??

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? 有一個嗎??

#1樓

參考:https://stackoom.com/question/449d/如何將ISO-日期時間字符串轉換為Python日期時間對象-重復

#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. 這還包括毫秒和時區。??

?If the time is '2012-09-30T15:31:50.262-08:00', this will convert into epoch time. 如果時間是“ 2012-09-30T15:31:50.262-08:00”,則它將轉換為紀元時間。??

>>> 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對此很有希望:??

>>> 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是一個Python庫,它提供了一種明智,智能的方式來創建,操作,格式化和轉換日期和時間。 Arrow is simple, lightweight and heavily inspired by moment.js and requests . Arrow很簡單,輕巧,并且受moment.js和request的啟發很大 。??

#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. 您應該注意時區信息,因為在比較非tz感知的日期時間和tz感知的日期時間時可能會遇到麻煩。??

?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意識(即使僅作為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應該處理這個問題。 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. 它還了解時區,Python 2和Python 3,并且在需要時可以合理涵蓋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允許存在許多可選的冒號和破折號,因此基本上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. 目標是生成UTC日期時間對象。??

?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. 如果要處理時區偏移,例如2016-06-29T19:36:29.3453-0400或2008-09-03T20:56:35.450686+05:00使用以下內容。 These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse. 這些會將所有變體轉換成沒有變量定界符的內容,例如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). 如果您的系統不支持%z strptime指令(您會看到類似ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z' ),則需要手動從Z (UTC)偏移時間。 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版本中無法在您的系統上運行,因為它取決于C庫支持,該支持因系統/ Python構建類型(即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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容