【问题标题】:Python 3 Pandas Timestamp Date ParsePython 3 Pandas 时间戳日期解析
【发布时间】:2018-06-20 23:13:43
【问题描述】:

我有一些来自 API 请求的时间序列数据,当我在处理一些数据时,下面会弹出这个错误。数据争论只是一些简单的 Pandas 系列数学(未显示)。

TypeError:-: 'str' 和 'str' 的操作数类型不受支持

但是当我将数据保存到 CSV 时:

elecMeter_df.to_csv('C:\\Python Scripts\\elecMeter_df.csv', sep=',', header=True, index=True, na_rep='N/A')

然后在 read_CSV 上解析日期:

elecMeter_dfCSV = pd.read_csv('C:\\Python Scripts\\elecMeter_df.csv', index_col='Date', parse_dates=True)

我没有收到上述原始错误。为什么会这样?我收到错误是因为时间戳是一个字符串,我需要转换为整数格式吗?

当我收到错误时,索引是这种格式:

print(elecMeter_df.index)

但是当读取 CSV 文件并解析日期列时(数据整理过程中没有错误,索引是这种格式:(没有芝加哥时区参考)

print(elecMeter_df.index)

任何可以向我解释有关时间戳以及为什么会发生此错误的帮助/提示将不胜感激。 Utilimetely 我试图不必使用读/写 CSV 进程,但如果它是唯一不会出现任何错误的方法,我会坚持下去!

【问题讨论】:

  • 您要解析的数据的type() 是什么?什么是解析操作(例如,是pd.to_datetime()),你有麻烦working with time zones。另外,请不要粘贴输出,将其放在代码块中。
  • 什么命令导致了这个错误? PS 我看到的唯一区别是一个索引是 TZ 感知的(美国/芝加哥),而第二个不是
  • @Henry 我认为 CSV 解决方法只是忽略 TZ 偏移量,这会扰乱你的日期时间转换,因为它通常是 -0500 而不是 -05:00 - 你能假设所有您的数据是芝加哥时间,还是需要 TZ 感知解决方案
  • 好吧,对不起,输出的片段:)我记得以后不要这样做...... MetaDataFrame 似乎是类型
  • AttributeError: 'MetaDataFrame' 对象没有属性 'to_datetime'

标签: python-3.x pandas csv datetime timestamp


【解决方案1】:

不确定您正在运行什么代码来生成该错误。但是,时间戳可能需要从字符串转换为日期时间。尝试使用 pd.to_datetime,另外您可以指定格式(选项列表和含义在下面提供)。我用于格式的示例是年-月-日时-分。

pd.to_datetime(df['column'], format = %Y-%m-%d %H:%M)



%a  Locale’s abbreviated weekday name.
%A  Locale’s full weekday name.      
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%f  Microsecond as a decimal number [0,999999], zero-padded on the left
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].      
%p  Locale’s equivalent of either AM or PM.
%S  Second as a decimal number [00,61].
%U  Week number of the year (Sunday as the first day of the week)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  UTC offset in the form +HHMM or -HHMM.
%Z  Time zone name (empty string if the object is naive).    
%%  A literal '%' character.

【讨论】:

  • 这没有回答问题
猜你喜欢
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多