ISO 8601 datetime 문자열을 Python datetime 개체로 변환하려면 어떻게 해야 합니까?
'2009-05-28T16:15:00'(ISO 8601일)입니다. 중 하나는 '해키시'를 사용하여 입니다.time.strptime
날짜 생성자
datetime.datetime(*time.strptime("2007-03-04T21:08:12", "%Y-%m-%dT%H:%M:%S")[:6])
나는 이것을 "더 깨끗한" 방법을 찾을 수 없었다.있어요?
시간대 처리 및 일반적으로 솔리드 날짜 파싱에는 dateutil 라이브러리를 사용하는 것이 좋습니다.만약 당신이 그것을 얻을 수 있다면ISO 8601
" "와 같은 문자열:2010-05-08T23:41:54.000Z
을 사용하면 되어 있는지 알 수 없는 해석할 수 strptime은 시간대가포함되어 있는지 여부를 알 수 없습니다. pyiso8601
사용 중 우연히 발생한 몇 가지 문제(트래커 확인)가 있으며, 몇 년 동안 업데이트되지 않았습니다. 반면 dateutil은 활성화되어 작동했습니다.
from dateutil import parser
yourdate = parser.parse(datestring)
Python 3.7과 외부 라이브러리가 없으므로 datetime 모듈에서 fromisoformat 함수를 사용할 수 있습니다.
datetime.datetime.fromisoformat('2019-01-04T16:41:24+0200')
Python 2를 .%z
포맷 지정자이므로 가능하면 어디에서나 Zulu 시간을 명시적으로 사용하는 것이 좋습니다.
datetime.datetime.strptime("2007-03-04T21:08:12Z", "%Y-%m-%dT%H:%M:%SZ")
ISO 할 수 때문에 기본적으로 ISO 8601은 콜론이나 를 사용할 수 있습니다.CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]
이러한해야 합니다.strptime 을 . 。
목표는 UTC datetime 객체를 생성하는 것입니다.
에 UTC의 예: 「UTC」).2016-06-29T19:36:29.3453Z
:
datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")
을 취급하는 는, 「」와 같이 해 .2016-06-29T19:36:29.3453-0400
★★★★★★★★★★★★★★★★★」2008-09-03T20:56:35.450686+05:00
다음을 사용합니다. 모든 됩니다.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" )
이 " " 를 하지 않는 %z
디렉티브 directive 등)ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z'
)에서 수동으로 Z
UTC주(UTC) 주%z
Python 버전 < 3에서는 시스템/Python 빌드 타입(Jython, Cython 등)에 따라 다른C 라이브러리의 지원에 의존하기 때문에, 사용의 시스템에서는 동작하지 않는 경우가 있습니다.
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
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는 날짜와 시간을 만들고, 조작하고, 포맷하고, 변환할 수 있는 현명하고, 지능적인 방법을 제공하는 Python 라이브러리입니다.Arrow는 심플하고 가벼우며 moment.js와 요청에 크게 영감을 받았습니다.
tz 인식 이외의 데이터 타임과 tz 인식의 데이터 타임의 비교에 문제가 발생할 가능성이 있기 때문에, 타임 존 정보에 주의해 주세요.
tz-aware로 하는 것이 가장 좋은 방법일 것입니다(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
#-----------------------------------------------
아직 시도하지 않았지만, pyiso8601이 이것을 지원하겠다고 약속합니다.
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
여기에는 밀리초와 타임존도 포함됩니다.
시간이 '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
양쪽 모두:
Epoch to ISO 시간:
isoTime = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(epochTime))
ISO Epoch까지의 시간:
epochTime = time.mktime(time.strptime(isoTime, '%Y-%m-%dT%H:%M:%SZ'))
이소데이트가 가장 완벽한 지원을 하는 것 같다.
aniso8601은 이 처리를 해야 합니다.또한 타임존, Python 2 및 Python 3을 이해하고 필요할 경우 ISO 8601의 나머지 부분에 대한 합리적인 적용 범위가 있습니다.
import aniso8601
aniso8601.parse_datetime('2007-03-04T21:08:12')
여기 이런 종류의 변환을 수행하는 매우 간단한 방법이 있습니다.구문 분석이나 추가 라이브러리가 필요하지 않습니다.그것은 깨끗하고, 단순하고, 빠르다.
import datetime
import time
################################################
#
# Takes the time (in seconds),
# and returns a string of the time in ISO8601 format.
# Note: Timezone is UTC
#
################################################
def TimeToISO8601(seconds):
strKv = datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d')
strKv = strKv + "T"
strKv = strKv + datetime.datetime.fromtimestamp(seconds).strftime('%H:%M:%S')
strKv = strKv +"Z"
return strKv
################################################
#
# Takes a string of the time in ISO8601 format,
# and returns the time (in seconds).
# Note: Timezone is UTC
#
################################################
def ISO8601ToTime(strISOTime):
K1 = 0
K2 = 9999999999
K3 = 0
counter = 0
while counter < 95:
K3 = (K1 + K2) / 2
strK4 = TimeToISO8601(K3)
if strK4 < strISOTime:
K1 = K3
if strK4 > strISOTime:
K2 = K3
counter = counter + 1
return K3
################################################
#
# Takes a string of the time in ISO8601 (UTC) format,
# and returns a python DateTime object.
# Note: returned value is your local time zone.
#
################################################
def ISO8601ToDateTime(strISOTime):
return time.gmtime(ISO8601ToTime(strISOTime))
#To test:
Test = "2014-09-27T12:05:06.9876"
print ("The test value is: " + Test)
Ans = ISO8601ToTime(Test)
print ("The answer in seconds is: " + str(Ans))
print ("And a Python datetime object is: " + str(ISO8601ToDateTime(Test)))
언급URL : https://stackoverflow.com/questions/969285/how-do-i-translate-an-iso-8601-datetime-string-into-a-python-datetime-object
'itsource' 카테고리의 다른 글
느린 SecureRandom 제너레이터에 대처하는 방법 (0) | 2022.11.24 |
---|---|
인터페이스에는 스태틱메서드가 없지만 스태틱필드와 내부 클래스는 정상인 이유는 무엇입니까?[Java8 이전] (0) | 2022.11.24 |
Symfony 2에서 모든 요청 매개 변수 가져오기 (0) | 2022.11.24 |
Python에서 SIGINT를 캡처하려면 어떻게 해야 하나요? (0) | 2022.11.24 |
중복되지 않은 값 삽입 (0) | 2022.11.15 |