更改时间戳的utcoffset [英] Change utcoffset of a Timestamp

查看:177
本文介绍了更改时间戳的utcoffset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有时您在时区之间进行转换时,Python会困惑于结果应该是什么,因为时区很难.

I know that sometimes when you're converting between timezones Python gets confused about what the result should be, because timezones are hard.

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分钟.

Obviously the offset should not be four hours and 56 minutes.

如果发现错误,是否有办法坚持您的utcoffset应该是什么?

When it gets it wrong, is there a way to insist on what you the utcoffset should be?

我只是在美国/东部"和"UTC"之间转换,因此偏移量应该只能是4到5个小时.我要检查的是偏移量是否为整数小时,如果不是,则四舍五入到最接近的数字.

I'm only converting between 'US/Eastern' and 'UTC', so the offset should only ever be four or five hours. What I'd like to do is check to see if the offset is an integer number of hours, and then round to the nearest number if not.

推荐答案

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

Before 1901-12-13 20:45:52, the utcoffset was 4 hours and 56 minutes.

您可以使用pytz进行确认,该pytz使用 Olson数据库.这与Pandas用于执行时区计算的模块相同:

You can confirm this using pytz which uses the Olson database. This is the same module that Pandas uses to perform timezone calculations:

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(以秒为单位).前几行看起来像这样

This prints all the utc transition boundaries and utcoffets (in seconds) for the US/Eastern timezone. The first few lines look like this

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分钟).

So before 1901-12-13 20:45:52, the utcoffset was -17760 seconds (or, equivalently, 4 hours and 56 minutes).

使用pytz从本地时间制作时区感知日期的标准方法是调用localize方法:

The standard way to make a timezone-aware date from a localtime using pytz is to call the localize method:

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

这可以确认熊猫返回的时间戳是正确的:

This confirms that the Timestamp returned by Pandas is correct:

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

这篇关于更改时间戳的utcoffset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆