如何将timedelta转换为熊猫的时间?

时间:2015-12-28 22:51:16

标签: python pandas datetime time timedelta

我有一个包含mySQL time类型数据的SQL表,如下所示:

time_of_day
-----------
   12:34:56

然后我使用pandas来阅读以下表格:

df = pd.read_sql('select * from time_of_day', engine)

查看df.dtypes收益率:

time_of_day timedelta64[ns]

我的主要问题是,在将df写入csv文件时,数据全部搞砸了,而不是基本上看起来像我的SQL表:

time_of_day
0 days 12:34:56.000000000

我希望(显然)将此记录存储为time,但我无法在大熊猫文档中找到任何有关时间的内容{{1} }。

pandas是否故意缺少此功能?有没有办法解决我的问题,而不需要janky数据投射?

这似乎应该是基本的,但我感到很困惑。

3 个答案:

答案 0 :(得分:2)

找到了解决方案,但我觉得它必须比这更优雅:

def convert(x):
    return pd.to_datetime(x).strftime('%H:%M:%S')

df['time_of_day'] = df['time_of_day'].apply(convert)

答案 1 :(得分:0)

答案 2 :(得分:0)

熊猫不支持time dtype系列

熊猫(和NumPy)没有time dtype。由于希望避免使用熊猫timedelta,因此有3种选择:熊猫datetime,Python datetime.time或Python str。下面按优先顺序显示它们。假设您从以下数据帧开始:

df = pd.DataFrame({'time': pd.to_timedelta(['12:34:56', '05:12:45', '15:15:06'])})

print(df['time'].dtype)  # timedelta64[ns]

熊猫datetime系列

您可以使用熊猫datetime系列,并包含任意日期成分,例如今天的日期。此类序列的基础是整数,这使该解决方案最有效且最适用。

默认日期(如果未指定)为1970年1月1日:

df['time'] = pd.to_datetime(df['time'])

print(df)

#                  time
# 0 1970-01-01 12:34:56
# 1 1970-01-01 05:12:45
# 2 1970-01-01 15:15:06

您还可以指定日期,例如今天:

df['time'] = pd.Timestamp('today').normalize() + df['time']

print(df)

#                  time
# 0 2019-01-02 12:34:56
# 1 2019-01-02 05:12:45
# 2 2019-01-02 15:15:06

熊猫object系列的Python datetime.time

标准库中的Python datetime模块支持datetime.time对象。您可以将系列转换为包含指向object对象序列的指针的datetime.time dtype系列。运算将不再进行矢量化处理,但每个基础值将在内部由数字表示。

df['time'] = pd.to_datetime(df['time']).dt.time

print(df)

#        time
# 0  12:34:56
# 1  05:12:45
# 2  15:15:06

print(df['time'].dtype)
# object

print(type(df['time'].at[0]))
# <class 'datetime.time'>

熊猫object系列的Python str

仅出于演示目的,建议仅将其转换为字符串,而其他类型则不支持。熊猫datetime或Python datetime.time。例如:

df['time'] = pd.to_datetime(df['time']).dt.strftime('%H:%M:%S')

print(df)

#        time
# 0  12:34:56
# 1  05:12:45
# 2  15:15:06

print(df['time'].dtype)
# object

print(type(df['time'].at[0]))
# <class 'str'>