【问题标题】:Python pandas dataframe conversion to unixtime [duplicate]Python pandas数据帧转换为unixtime [重复]
【发布时间】:2020-05-27 20:43:47
【问题描述】:

我想在 unix 时间戳中转换格式为 yyyy=year, mm=month, dd=day, hh=hour, nn=minute 的日期。 我试过了:

df_out['unixtime'] = datetime(df_out['yyyymmddhhmm'].dt.year.to_numpy(),df_out['yyyymmddhhmm'].dt.month.to_numpy(),df_out['yyyymmddhhmm'].dt.day.to_numpy(),df_out['yyyymmddhhmm'].dt.hour.to_numpy(),df_out['yyyymmddhhmm'].dt.minute.to_numpy()).timestamp()

但我收到了错误消息:

TypeError:只有 size-1 的数组可以转换为 Python 标量

我做错了什么?

非常感谢任何帮助!

问候, 亚历山大

【问题讨论】:

  • 请与预期输出共享数据框的示例输入。
  • 请与我们分享输入

标签: python pandas dataframe unix-timestamp


【解决方案1】:

officially 推荐的方法是减去纪元,然后除以“单位”(1 秒):

df = pd.DataFrame({'yyyymmddhhmm': pd.to_datetime(['20201108121314', '20201109121314'])})

df['unixtime'] = (df.yyyymmddhhmm - pd.Timestamp('1970-01-01')) // pd.Timedelta('1s')

结果:

         yyyymmddhhmm    unixtime
0 2020-11-08 12:13:14  1604837594
1 2020-11-09 12:13:14  1604923994

【讨论】:

    【解决方案2】:

    您可以使用 pandas 库为日期创建单列

     df_out['date_format'] = pd.to_datetime(df_out['date_time_column'], format='%Y%m%d%H%M')
    

    然后您可以创建由年、月、日、小时信息组成的新列

    pd.DatetimeIndex(df_out['date_format']).year 
    pd.DatetimeIndex(df_out['date_format']).month 
    pd.DatetimeIndex(df_out['date_format']).day 
    pd.DatetimeIndex(df_out['date_format']).hour
    

    【讨论】:

      猜你喜欢
      • 2021-11-16
      • 2019-05-17
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 2019-06-01
      • 2019-01-16
      • 1970-01-01
      相关资源
      最近更新 更多