【问题标题】:Convert timestamp with timezone info to corrected timestamp?将带有时区信息的时间戳转换为更正的时间戳?
【发布时间】:2020-11-27 13:17:05
【问题描述】:

我有一列 timestamps 包含时区信息。它是通过数据库中的 SQL 查询导入的。它的数据类型为datetimeoffset(7)

2020-06-04 13:00:00.0000000 +02:00

如何将其转换为考虑tz 信息的天真日期,例如。

2020-06-04 15:00:00

请注意,+ 02:00 部分已添加到 timestamp,而不是简单地删除。

timestamps 存储在 pandas dataframe 中。

【问题讨论】:

  • 注意:从技术上讲,第一次考虑时区,第二次没有,它只是一个“挂钟”,没有人知道时区。你使用的时区不正确:你应该 substract 时区偏移量(或 UTC 时间 + 偏移量 = 本地时间)。pandas 应该能够处理时区(实际上时间以相同的 UTC 格式存储,并且附加字段具有 +2,以防万一你让 pandas 打印时间。
  • 我假设“时间戳”是 pd.DataFrame(即 pd.Series)中的一列?它是什么类型的?我假设对象(字符串) - 正是这种格式'07-08-2020 08:00:00 + 02:00'
  • 是的,'TimeStamp' 是 pandas df 中的列/系列。该表是通过 SQL 查询从具有数据类型 datetimeoffset(7) 的数据库中导入的。
  • 好的,看来您可以从我的回答中省略df['timestamp'] = df['timestamp'].str.replace(r'(\+|\-)\ ', r'\1') 行;-)

标签: python pandas datetime timezone


【解决方案1】:

如果我正确地回答了问题,您需要天真本地时间,具体取决于您运行脚本的操作系统时区设置:

import pandas as pd
from tzlocal import get_localzone

# example data...
df = pd.DataFrame({'timestamp': ["07-08-2020 08:00:00 + 02:00"]})

# cast to datetime, in case you haven't already done this
# we need to strip a space first...
df['timestamp'] = df['timestamp'].str.replace(r'(\+|\-)\ ', r'\1')
df['timestamp'] = pd.to_datetime(df['timestamp'])

# df['timestamp']
# 0   2020-07-08 08:00:00+02:00
# Name: timestamp, dtype: datetime64[ns, pytz.FixedOffset(120)]

# now we can convert to local timezone, which will give us aware local time
df['localtime'] = df['timestamp'].dt.tz_convert(get_localzone())

# ...and remove the tzinfo to get naive datetime:
df['localtime'] = df['localtime'].dt.tz_localize(None)
    
# note that my machine is on UTC+2 -->
# df['localtime']
# 0   2020-07-08 08:00:00
# Name: localtime, dtype: datetime64[ns]

...但请记住,这将modify the internal timestamps...

【讨论】:

    【解决方案2】:

    首先获取 UTC 偏移量,例如: 使用这个熊猫功能。您也可以使用 pytz 模块来获取 UTC 偏移时间。

    pandas.Timestamp.utcoffset¶
    

    从日期时间中提取 UTCoffset 小时后: 然后只需添加 using pandas timedelta 函数: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Timedelta.html 例如:这样做:

    df['time'] = df['time'].dt.tz_convert(None) + pd.Timedelta(2, unit='h')
    

    【讨论】:

    • 为澄清起见,我正在尝试将 UTC 自动转换为客户本地时间,因此在这种情况下,不能选择使用 + pd.Timedelta(2, unit='h') 等手动计算偏移量.我正在寻找一种将时区感知时间戳转换为将时区信息集成到时间部分中的时间戳的函数。
    • 为什么不呢?使用 pandas 函数计算 UTCoffset 并将其保存在例如名为 offset 的 coumn 中,然后使用上面的 timedelta 函数简单地添加。有很多方法可以做到这一点。
    • 好的,但是如何从我的时间戳 07-08-2020 08:00:00 + 02:00 中提取“2”部分?我假设在 python pandas 或 pytz 中会有一个自动进行转换的时间感知函数。
    猜你喜欢
    • 2018-12-18
    • 1970-01-01
    • 2021-09-22
    • 2019-10-07
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多