如何将所有熊猫的datetime列都转换为相同的时区

py_*_*oob 5 python timezone datetime type-conversion pandas

我有一个带有DataTime列的数据框(时区的格式不同)。看来时区是UTC,但我想将列转换为pd.to_datetime,但失败了。那就是问题1。由于失败了,因此我无法在该时间段上执行任何datetime操作,例如按日期分组/确定日期/按小时分组等等。这是我的数据框df_res

    DateTime
    2017-11-02 19:49:28-07:00
    2017-11-27 07:32:22-08:00
    2017-12-27 17:01:15-08:00
Run Code Online (Sandbox Code Playgroud)

命令的输出

      df_res["DateTime"] = df_res["DateTime"].dt.tz_convert('America/New_York')
Run Code Online (Sandbox Code Playgroud)

AttributeError: Can only use .dt accessor with datetimelike values

当我转换为 datetime

   df_res['DateTime'] = pd.to_datetime(df_res['DateTime'])
Run Code Online (Sandbox Code Playgroud)

ValueError: Tz-aware datetime.datetime cannot be converted to datetime64 unless utc=True

我觉得我正在转圈。我需要将列转换为日期时间才能执行操作,并且为了做到这一点,我需要将它们全部设置为相同的时区,但除非具有日期时间对象,否则我就不能使用相同的时区,因此,如何最好地实现这一点。我确实提到了以前的帖子,但它们似乎尽可能容易地转换为日期时间:

将datetime列转换为其他时区pandas 将pandas时区感知的DateTimeIndex转换为朴素时间戳,但在特定时区

JLM*_*JLM 15

我认为没有必要应用 lambdas:

df_res['DateTime'] = pd.to_datetime(df_res['DateTime'], utc=True)
Run Code Online (Sandbox Code Playgroud)

文档:https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

  • 仅当您的日期时间实际上采用 UTC 时,这才有效,对吗? (2认同)

Cez*_*ulc 7

你可以检查这个:

df = pd.DataFrame({
    'time': [
        '2017-11-02 19:49:28-08:00', 
        '2017-11-27 07:32:22-07:00', 
        '2017-12-27 17:01:15-07:00'
    ]
})

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

df['time'].apply(lambda x: pd.to_datetime(x).tz_localize('US/Eastern'))
Run Code Online (Sandbox Code Playgroud)
0   2017-11-03 03:49:28-04:00
1   2017-11-27 14:32:22-05:00
2   2017-12-28 00:01:15-05:00
Name: time, dtype: datetime64[ns, US/Eastern]
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,我需要将 `utf=True` arg 传递给 `pd.to_datetime()`,如 `df['time'] = pd.to_datetime(df['time'], utf=True)` (2认同)