2015-06-23 16 views
9

Gibt es eine Möglichkeit, Zeitzone im Format "+00: 00" mit strptime zu analysieren? Zum Beispiel:Parsing Zeitzone mit Doppelpunkt

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (In 
tel)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> from datetime import datetime 
>>> datetime.strptime("12:34:56+0000", "%X%z") 
datetime.datetime(1900, 1, 1, 12, 34, 56, tzinfo=datetime.timezone.utc) 
>>> datetime.strptime("12:34:56+00:00", "%X%z") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "C:\Python34\lib\_strptime.py", line 500, in _strptime_datetime 
    tt, fraction = _strptime(data_string, format) 
    File "C:\Python34\lib\_strptime.py", line 337, in _strptime 
    (data_string, format)) 
ValueError: time data '12:34:56+00:00' does not match format '%X%z' 

Irgendwelche Ideen?

+0

verwandt: [Konvertieren Zeitstempel mit Offset zu Datetime Obj mit Strptime] (http://stackoverflow.com/q/12281975/4279) – jfs

Antwort

4

Derzeit gibt es keine Heilung für diese, und hier ist und Erläuterung: https://bugs.python.org/issue15873 genauer gesagt, hier: https://bugs.python.org/msg169952. Aber Sie können dieses Problem außer Kraft setzen, auf diese Weise:

from datetime import datetime 
d = "2015-04-30T23:59:59+00:00" 
if ":" == d[-3:-2]: 
    d = d[:-3]+d[-2:] 
print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z")) 
0

Sie können auch Pandas verwenden:

import pandas as pd 
t = pd.to_datetime("2015-04-30T23:59:59+00:00") 

die Sie einen Zeitstempel Objekt geben:

t.hour 
Out[139]: 14 

t.day 
Out[140]: 30 
1

Eine andere Lösung ist, Verwende die dateutil-Bibliothek:

from dateutil import parser 

mystr = '2015-04-30T23:59:59+00:00' 

x = parser.parse(mystr) 

# 2015-04-30 23:59:59+00:00 
Verwandte Themen