gpt4 book ai didi

python - 使用 Python 将具有不同 UTC 基准​​的时间戳列转换为当前 UTC

转载 作者:太空狗 更新时间:2023-10-30 01:46:11 29 4
gpt4 key购买 nike

我有一个数据框,其时间戳是自 2010 年 1 月 1 日午夜 UTC 时区以来的秒数。我需要将它们转换为当前的 UTC 时间。我可以使用 timedelta 对给定的行执行此操作,但无法对整个时间戳列执行此操作。

    # The base of my timestamp is UTC(2010 Jan 1, midnight)
# able to do it for a specific delta i.e. df["timestamp][0]
sec_shift = pd.Timedelta(seconds=201852000)
new_time = datetime.datetime(2010,1,1)+sec_shift

# how do i do this for the entire df["timestamp"] column?
df = pd.DataFrame({"timestamp":[201852000,201852060,201852120,201852180,201852240], "B":[160863892,160864264,160864637,160865009,160865755]})

最佳答案

试试这个:

dif = (datetime.datetime(2010,1,1) - datetime.datetime(1970,1,1)).total_seconds()
sec_shift = 4*60*60
pd.to_datetime(df.timestamp + diff + sec_shift, unit='s')

演示:

In [29]: pd.to_datetime(df.timestamp + dif + sec_shift, unit='s')
Out[29]:
0 2016-05-25 10:00:00
1 2016-05-25 10:01:00
2 2016-05-25 10:02:00
3 2016-05-25 10:03:00
4 2016-05-25 10:04:00
Name: timestamp, dtype: datetime64[ns]

PS 我建议您使用标准解决方案,例如存储自 1970 年 1 月 1 日午夜 UTC(标准 UNIX 时间戳)以来的秒数 - 这将使您的工作更简单

关于python - 使用 Python 将具有不同 UTC 基准​​的时间戳列转换为当前 UTC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38020396/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com