1
from StringIO import StringIO
import datetime as dt
import pandas as pd

def addtime(temp):
    temp = (temp) + (dt.timedelta(hours  =16))
    return(temp)

data = """\
    '12-31-2012',5100, 5200
    '01/1/2013',5300,5400"""

tdata = pd.read_csv(StringIO(data),
    names =    ['date', 'field1', 'field'], index_col = None,
    parse_dates =['date'], header= None)

print tdata

old_date = tdata.ix[0,'date']
print 'old date =',old_date
new_date = addtime(old_date)
print 'new date =',new_date

#                 date  field1  field
#0  2012-12-31 00:00:00    5100   5200
#1  2013-01-01 00:00:00    5300   5400
#old date = 2012-12-31 00:00:00
#new date = 2012-12-31 16:00:00

作为 Pandas CSV 阅读器的一部分,我想为每个日期添加 16 个小时。但我不知道如何添加有效的“parse_dates=”。示例代码正确地执行了操作,只是不是以期望的方式。帮助将不胜感激。

4

1 回答 1

4

使用date_parser参数。通常,它默认为dateutil.parser.parse,但您可以指定一个自定义函数(例如addtime,下面),它不仅可以解析日期字符串,还可以添加 a timedelta

from StringIO import StringIO
import datetime as dt
import pandas as pd
import dateutil.parser as parser

def addtime(temp):
    temp = parser.parse(temp) + dt.timedelta(hours=16)
    return temp

data = """\
    '12-31-2012',5100, 5200
    '01/1/2013',5300,5400"""

tdata = pd.read_csv(StringIO(data),
    names = ['date', 'field1', 'field'], index_col = None,
    parse_dates =['date'], header= None, date_parser=addtime)

print tdata

产量

                  date  field1  field
0  2012-12-31 16:00:00    5100   5200
1  2013-01-01 16:00:00    5300   5400
于 2013-03-17T19:36:02.820 回答