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

本文翻譯自:How do I translate an ISO 8601 datetime string into a Python datetime object? [duplicate]

This question already has an answer here: 這個問題已經在這裏有了答案:

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.jsrequest的啓發很大


#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-04002008-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構建類型(即JythonCython等)而異。

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章