我知道,有时当您在时区之间转换时,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应该是什么?
我只在'US/Eastern'和'UTC'之间转换,所以偏移量应该只有四五个小时我想做的是检查偏移量是否为整数小时数,如果不是,则四舍五入到最接近的数字。

最佳答案

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转换边界和utcoffet(以秒为单位)。前几行是这样的
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分钟)。
使用pytz从本地时间创建时区感知日期的standard way方法是调用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

这确认熊猫返回的时间戳是正确的:
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

10-06 08:51