2012-05-08 17 views
34

Ho una stringa di data e ora che non so come analizzarla in Python.Parsing time string in Python

La stringa è così:

Tue May 08 15:14:45 +0800 2012 

Ho provato

datetime.strptime("Tue May 08 15:14:45 +0800 2012","%a %b %d %H:%M:%S %z %Y") 

ma Python solleva

'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y' 

Secondo Python doc:

%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

Qual è il formato corretto per analizzare questa stringa temporale?

+0

correlati: [Python: l'analisi data con fuso orario da un'e-mail] (http://stackoverflow.com/q/1790795/4279) – jfs

risposta

55

datetime.datetime.strptime ha problemi con l'analisi fuso orario. Dai un'occhiata al dateutil package:

>>> from dateutil import parser 
>>> parser.parse("Tue May 08 15:14:45 +0800 2012") 
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800)) 
+0

qualche idea su come analizzare' 02/Nov/2012: 06: 37: 42 + 0000'? Questo è il formato utilizzato da nginx nei file di log e 'parser.parse' restituisce' ValueError: unknown string format'. – zidarsk8

+0

@ zidarsk8: è necessario prima rimuovere i due punti dopo la data: '' 'parser.parse (" 06/Apr/2014: 13: 23: 04 ".replace (": "," ", 1))' ' ' –

+8

@ zidarsk8 prova questo:' parser.parse ("02/Nov/2012: 06: 37: 42 +0000", fuzzy = True) '- Specificando fuzzy, il parser ignora i caratteri che non capisce. – drevicko

1
In [117]: datetime.datetime.strptime? 
Type:   builtin_function_or_method 
Base Class:  <type 'builtin_function_or_method'> 
String Form: <built-in method strptime of type object at 0x9a2520> 
Namespace:  Interactive 
Docstring: 
    string, format -> new datetime parsed from a string (like time.strptime()). 
+1

Ho provato 'datetime.strptime (" Tue May 08 15:14:45 +0800 2012 ","% a% b% d% H:% M:% S% z% Y ")', ma Python genera ''z' è una direttiva errata nel formato '% a% b% d% H:% M:% S% z% Y' ' – xiaohan2012

13

La cosa migliore è quella di avere uno sguardo a strptime()

Qualcosa sulla falsariga di

>>> from datetime import datetime 
>>> date_str = 'Tue May 08 15:14:45 +0800 2012' 
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y') 
>>> date 
datetime.datetime(2012, 5, 8, 15, 14, 45) 

Im non sicuro di come fare il fuso orario 0800 sfortunatamente, forse qualcun altro può aiutarlo.

Le stringhe di formattazione possono essere trovate in http://docs.python.org/library/time.html#time.strftime e sono le stesse per la formattazione della stringa per la stampa.

Speranza che aiuta

Mark

PS, la soluzione migliore per fusi orari di installazione pytz da PyPI. (http://pytz.sourceforge.net/) in effetti penso che pytz abbia un ottimo metodo di analisi datetime se ricordo bene. La lib standard è un po 'sottile sulla terra con funzionalità timezone.

+0

eumiro cita 'datetime.datetime.strptime' ha problemi con l'analisi del fuso orario. Penso sia vero – xiaohan2012

3

Ha discusso molte volte in SO. In breve, "% z" non è supportato perché la piattaforma non lo supporta. La mia soluzione è una nuova, basta saltare il fuso orario .:

datetime.datetime.strptime(re.sub(r"[+-]([0-9])+", "", "Tue May 08 15:14:45 +0800 2012"),"%a %b %d %H:%M:%S %Y") 
3

Ecco una soluzione stdlib che supporta un offset nella stringa di tempo di ingresso UTC variabile:

>>> from email.utils import parsedate_tz, mktime_tz 
>>> from datetime import datetime, timedelta 
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012')) 
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp) 
>>> utc_time 
datetime.datetime(2012, 5, 8, 7, 14, 45)