【问题标题】:Change utcoffset of a Timestamp更改时间戳的 utcoffset
【发布时间】:2017-05-09 08:00:17
【问题描述】:

我知道有时当您在时区之间转换时,Python 会对结果应该是什么感到困惑,因为时区很难。

from pandas import Timestamp

string = "1900-01-01 00:00:00"
ts = Timestamp(string, tz='US/Eastern')
print(ts)

Timestamp('1900-01-01 00:00:00-0456', tz='US/Eastern')

显然,偏移量不应为 4 小时 56 分钟。

当它出错时,有没有办法坚持你的 utcoffset 应该是什么?

我只在“美国/东部”和“UTC”之间转换,所以偏移量应该只有四五个小时。我想做的是检查偏移量是否是整数小时数,如果不是,则四舍五入到最接近的数字。

【问题讨论】:

    标签: python datetime pandas


    【解决方案1】:

    在 1901-12-13 20:45:52 之前,utcoffset 为 4 小时 56 分钟。

    您可以使用使用Olson database 的pytz 来确认这一点。这与 Pandas 用于执行时区计算的模块相同:

    import pytz
    eastern = pytz.timezone('US/Eastern')
    for utcdate, info in zip(
            eastern._utc_transition_times, eastern._transition_info):
        utcoffset, dstoffset, tzabbrev = info
        print('{} | {} '.format(utcdate, utcoffset.total_seconds()))
    

    这会打印美国/东部时区的所有 utc 转换边界和 utcoffets(以秒为单位)。前几行是这样的

    0001-01-01 00:00:00 | -17760.0 
    1901-12-13 20:45:52 | -18000.0 
    1918-03-31 07:00:00 | -14400.0 
    1918-10-27 06:00:00 | -18000.0 
    1919-03-30 07:00:00 | -14400.0 
    ...
    

    因此,在 1901-12-13 20:45:52 之前,utcoffset 为 -17760 秒(或者,相当于 4 小时 56 分钟)。


    standard way 使用 pytz 从本地时间创建时区感知日期是调用 localize 方法:

    import datetime as DT
    import pytz
    eastern = pytz.timezone('US/Eastern')
    date = DT.datetime(1900,1,1)
    local_date = eastern.localize(date)
    print(local_date)
    

    打印

    1900-01-01 00:00:00-04:56
    

    这证实了 Pandas 返回的时间戳是正确的:

    import pandas as pd
    string = "1900-01-01 00:00:00"
    ts = pd.Timestamp(string, tz='US/Eastern')
    print(ts)
    # 1900-01-01 00:00:00-04:56
    

    【讨论】:

    • 如果我有权授予你一顶巫师帽……我会的!
    • 嗯,这是我今天学到的东西。我在这里责备pytz。出于好奇,您(或其他任何人)是否知道为什么偏移量是 4 小时 56 分钟?
    • 早在 19 世纪(和 20 世纪初)人们使用local mean time 而不是标准时间。
    • 干杯伙伴。非常感谢,
    猜你喜欢
    • 2018-11-27
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多