【问题标题】:convert dataframe column from timestamp with timezone to timestamp type将数据框列从带有时区的时间戳转换为时间戳类型
【发布时间】:2021-06-25 12:34:14
【问题描述】:

我有一个包含 3 列的数据框。数据框是从 Postgres 表创建的。

请问如何进行从 timestamptz 到 timestamp 的转换?

我做到了

df['StartTime'] = df["StartTime"].apply(lambda x: x.tz_localize(None))

StartTime 中的数据示例:

2013-09-27 14:19:46.825000+02:00
2014-02-07 10:52:25.392000+01:00

谢谢,

【问题讨论】:

  • 谢谢!我想像这样存储数据:2013-09-27 14:19:46, 2014-02-07 10:52:25 @MrFuppes
  • 啊,对了,既然您混合了 UTC 偏移量,您需要在尝试时应用 lambda。但是将 tzinfo 替换为 None 因为混合偏移意味着您正在处理日期时间对象 --> 使用 pd.to_datetime(df["StartTime"]).apply(lambda t: t.replace(tzinfo=None))
  • @MrFuppes 谢谢我收到此错误 **E ValueError: Tz-aware datetime.datetime cannot be convert to datetime64 unless utc=True **
  • 好的,如果 df 中的 Series 已经是 dtype datetime,只需使用 df["StartTime"].apply(lambda t: t.replace(tzinfo=None))

标签: python pandas datetime timestamp


【解决方案1】:

为了给出更全面的答案,这里的重点是,在您的示例中,您的时间戳具有混合 UTC 偏移量。如果不设置任何关键字,pandas 会将字符串转换为日期时间,但将系列的类型保留为原生 Python 日期时间,而不是pandas (numpy) datetime64。这使得使用像tz_localize 这样的内置方法有点困难。但是您可以按自己的方式工作。例如:

import pandas as pd
# exemplary Series
StartTime = pd.Series(["2013-09-27 14:19:46.825000+02:00", "2014-02-07 10:52:25.392000+01:00"])
# make sure we have datetime Series
StartTime = pd.to_datetime(StartTime)

# notice the dtype:
print(type(StartTime.iloc[0]))
# <class 'datetime.datetime'>

# we also cannot use dt accessor:
# print(StartTime.dt.date)
# >>> AttributeError: Can only use .dt accessor with datetimelike values

# ...but we can use replace method of datetime object and remove tz info:
StartTime = StartTime.apply(lambda t: t.replace(tzinfo=None))

# now we have
StartTime
0   2013-09-27 14:19:46.825
1   2014-02-07 10:52:25.392
dtype: datetime64[ns]

# and can use e.g.
StartTime.dt.date
# 0    2013-09-27
# 1    2014-02-07
# dtype: object

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2019-10-07
    • 2015-10-07
    相关资源
    最近更新 更多