2017-03-26 2 views
1

Pandasを使用して自分のデータのタイムスタンプを解析するのに問題があります。Pandasを使用している(わずかに)わかりにくいタイムゾーンのPython datetimesの文字列フォーマット

私が解析しようとしているdatetime形式の例は、2012-05-02 01:00:00-05:00のように見えます。 Pandasのドキュメントから、Python datetime formattingのドキュメントに進み、%Y-%m-%d %H:%M:%S%zのような書式設定文字列を使用することを提案しました。次のように

私は...

fmts = {"variable_name": `%Y-%m-%d %H:%M:%S%z`} 
df = pd.read_sql_query("SELECT * FROM some_table", con=some_engine, parse_dates=fmts) 

をフォーマット文字列を使用するこのソリューションは、データフレームを返されたが、要求された列の解析に失敗しました。これは、データのタイムゾーンコンポーネントに予期しないコロンがあるためです。私がタイムゾーンを指定した例は-05:00であり、%zの書式化文字列は-0500です。

これにアプローチする方法についてのご意見はありますか?

答えて

4

日付文字列形式を変換する関数をクックアップすることができます。その後、列に適用してdatetimesに変換することができます。この関数は、タイムゾーンaware or naive timestampsを返すことができます。

コード:

import datetime as dt 
import pytz 

def convert_to_datetime(tz=None): 
    """ Convert our custom timezone representation to a datetime 

    Timestamp looks like: 2012-05-02 01:00:00-05:00 

    :param tz: None, returns UTC relative Naive 
       True, returns timezone aware timestamp in UTC 
       <tz>, returns timezone aware timestamp in given timezone 
    :return: returns a processing function that can be passed to apply() 
    """ 

    def func(datetime_string): 
     time = datetime_string[:19] 
     tz_str = datetime_string[19:] 

     # parse the timezone offset to minutes and seconds 
     tz_offset = int(
      tz_str[0] + str(int(tz_str[1:3]) * 60 + int(tz_str[4:]))) 

     # return a datetime that is offset 
     result = dt.datetime.strptime(time, '%Y-%m-%d %H:%M:%S') - \ 
       dt.timedelta(minutes=tz_offset) 

     if tz is not None: 
      result = result.replace(tzinfo=pytz.UTC) 

      if tz is not True: 
       result = result.astimezone(tz) 
     return result 

    return func 

テストコード:

df = pd.DataFrame([ 
    '2012-05-02 01:00:00-05:00', 
    '2012-05-02 03:00:00-05:00'], 
    columns=['timestamp']) 

df['zulu_no_tz'] = df.timestamp.apply(convert_to_datetime()) 
df['utc_tz'] = df.timestamp.apply(convert_to_datetime(tz=True)) 
df['local_tz'] = df.timestamp.apply(convert_to_datetime(
    tz=pytz.timezone('US/Central'))) 
print(df) 

試験結果:

    timestamp   zulu_no_tz     utc_tz \ 
0 2012-05-02 01:00:00-05:00 2012-05-02 06:00:00 2012-05-02 06:00:00+00:00 
1 2012-05-02 03:00:00-05:00 2012-05-02 08:00:00 2012-05-02 08:00:00+00:00 

        local_tz 
0 2012-05-02 01:00:00-05:00 
1 2012-05-02 03:00:00-05:00 

用途dateutil

dateutilにアクセスできる場合は、解析コードを使用できます。これは上記のfuncの代わりであり、日付形式をうまく処理します。それはそれは夏時間ではないことを意味し、固定オフセットのタイムゾーンを、適用されるので、私はこのスタイルの巨大なファンではない

import dateutil 
df.timestamp.apply(dateutil.parser.parse) 

:としてあなたがまたapply()で裸dateutil.parserを使用することができます

import dateutil 

def func(datetime_string): 
    result = dateutil.parser.parse(datetime_string).astimezone(pytz.UTC) 

    if tz is None: 
     result = result.replace(tzinfo=None) 
    elif tz is not True: 
     result = result.astimezone(tz) 
    return result 

承知して。私は個人的に夏時間を意識しているか、単にUTCを好みます。

関連する問題