2017-09-22 169 views
1

我有不同類型的ISO 8601格式化日期字符串,使用datetime library,我想從這些字符串獲得datetime object。輸入串的Python ISO 8601日期時間解析

實施例:

  1. 2017-08-01(2017年8月1日)
  2. 2017-09(2017九月)
  3. 2017-W20(第20周)
  4. 2017-W37-2(37周的星期二)

我能夠獲得第一,第二和第四例但是對於第三,我在嘗試時得到了回溯。

我使用datetime.datetime.strptime功能爲他們在嘗試 - 除了塊,如下:

try : 
    d1 = datetime.datetime.strptime(date,'%Y-%m-%d') 
except : 
    try : 
     d1 = datetime.datetime.strptime(date,'%Y-%m') 
    except : 
     try : 
      d1 = datetime.datetime.strptime(date,'%G-W%V') 
     except : 
      print('Not going through') 

,當我試圖在終端第三try塊,這是我得到了

>>> dstr 
'2017-W38' 
>>> dt.strptime(dstr,'%G-W%V') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 565, in _strptime_datetime 
    tt, fraction = _strptime(data_string, format) 
    File "C:\Users\tushar.aggarwal\Desktop\Python\Python3632\lib\_strptime.py", line 483, in _strptime 
    raise ValueError("ISO year directive '%G' must be used with " 
ValueError: ISO year directive '%G' must be used with the ISO week directive '%V' and a weekday directive ('%A', '%a', '%w', or '%u'). 
錯誤

這是我得到了第4的情況下工作:

>>> dstr 
'2017-W38-2' 
>>> dt.strptime(dstr,'%G-W%V-%u') 
datetime.datetime(2017, 9, 19, 0, 0) 

這裏是參考對於我的代碼:strptime documentation

關於日期解析從ISO 8601格式SO上有很多問題,但我找不到解決我的問題。此外,涉及的問題是非常古老的,並採取老版本的Python,其中%G,%V指令strptime不可用。

+1

'datetime'中的解析是有限的。看看模塊'dateutil'。 – BoarGules

回答

0

pendulum圖書館在這些方面做得很好。

>>> import pendulum 
>>> pendulum.parse('2017-08-01') 
<Pendulum [2017-08-01T00:00:00+00:00]> 
>>> pendulum.parse('2017-09') 
<Pendulum [2017-09-01T00:00:00+00:00]> 
>>> pendulum.parse('2017-W20') 
<Pendulum [2017-05-15T00:00:00+00:00]> 
>>> pendulum.parse('2017-W37-2') 
<Pendulum [2017-09-12T00:00:00+00:00]> 

的頁面,我已經說你提到的鏈接,「庫本身支持RFC 3339的格式,最ISO 8601格式和其他一些常見的格式。如果你傳遞一個非標準的或更復雜的字符串,這個庫將在dateutil解析器上回退。

+0

獲得一個'Pendulum'對象(解析後)後,我可以從這個擺對象中獲得一個'datetime'對象嗎? –

+0

您不需要,因爲鐘擺從日期時間繼承。這是直接替換。除了在一個相當有限的情況下(見https://pendulum.eustace.io/faq/),你可以用datetime做任何事情,你可以用擺錘做更多的事情。只需輸入擺錘而不是日期。如果您確實想將實例轉換爲日期時間,請使用其一個或多個屬性,adate.year,adate.month,adate.day等。但這幾乎是不必要的。 –