【问题标题】:Timestamp subtraction must have the same timezones时间戳减法必须具有相同的时区
【发布时间】:2020-07-07 20:20:14
【问题描述】:

我不断收到以下错误:

  • TypeError:时间戳减法必须具有相同的时区或没有 时区

在这一行

df['days_in_Month'].loc[df['Month'] == min_date_Month] = (df['Month_end'] - \
                                                          pd.to_datetime(min_date,format="%Y-%m-%d"))

我的 df['TransactionDate'] 是一列,格式如下 2019-08-23T00:00:00.000Z。我正在 Python3.3.7 上编程。

df['Month'] = df['TransactionDate'].apply(lambda x : str(x)[:7])
df['Month_begin'] = pd.to_datetime(df['Month'], format="%Y-%m") + MonthBegin(0)
df['Month_end'] = pd.to_datetime(df['Month'], format="%Y-%m") + MonthEnd(1)

df['days_in_Month'] = (df['Month_end'] - df['Month_begin'])#.days()
print(df.columns)
print(df)

min_date = df['TransactionDate'].min()
min_date_Month = min_date[:7]

df['days_in_Month'].loc[df['Month'] == min_date_Month] = (df['Month_end'] - \
                                                          pd.to_datetime(min_date,format="%Y-%m-%d"))
df['Month_begin'].loc[df['Month'] == min_date_Month] = pd.to_datetime(min_date,format="%Y-%m-%d")

【问题讨论】:

    标签: python pandas dataframe datetime timestamp


    【解决方案1】:

    问题是日期时间字符串中的 Z 导致日期时间被解释为 utc 时区

    但是您的 Month_end 键没有附加任何时区信息,因此它没有与之关联的时区

    pandas 不知道如何与这两种不同的事物进行交互,因此您需要从日期时间字符串中删除时区,或者更好地让您的其他日期时间时区了解 UTC。

    pandas 让这变得相对容易

    Month_end = pandas.to_datetime(month_end_strings,utc=True)
    

    【讨论】:

      【解决方案2】:

      当你运行你的违规指令时:

      pd.to_datetime(min_date, format="%Y-%m-%d")
      

      你会得到:

      Timestamp('2019-11-01 00:00:00+0000', tz='UTC')
      

      表示format="%Y-%m-%d"不阻止这个功能 从解析 whole 输入字符串,所以结果是 with 时区。

      要解析日期部分,运行:

      pd.to_datetime(min_date[:10])
      

      (即使没有格式)你会得到:

      Timestamp('2019-11-01 00:00:00')
      

      没有时区。

      但是你的整个指令很奇怪。 当您单独运行左侧时:

      df['days_in_Month'].loc[df['Month'] == min_date_Month]
      

      你会得到:

      0   29 days
      Name: days_in_Month, dtype: timedelta64[ns]
      

      但是当你单独运行右手边时:

      df['Month_end'] - pd.to_datetime(min_date[:10])
      

      你会得到:

      0    29 days
      1    60 days
      2    91 days
      3   120 days
      Name: Month_end, dtype: timedelta64[ns]
      

      因此您尝试将整列保存在单个单元格下。

      也许这条指令应该是:

      df['days_in_Month'] =  df['Month_end'] - pd.to_datetime(min_date[:10])
      

      改为?

      还有一句话:您的 days_in_Month 列实际上是 timedelta64 类型,而不是天数。

      要获得每个月的天数(作为整数),您应该运行:

      df['days_in_Month'] = (df['Month_end'] - df['Month_begin']).dt.days + 1
      

      请注意,例如2019-11-012019-11-30 的区别 是 29 天,而 11 月有 30 天。

      【讨论】:

        猜你喜欢
        • 2019-12-15
        • 2021-10-17
        • 2020-06-29
        • 1970-01-01
        • 2012-02-04
        • 2016-05-18
        • 2013-11-17
        • 2013-10-30
        • 2016-07-19
        相关资源
        最近更新 更多