【问题标题】:How to convert from UTC to tzutc() timezone?如何从 UTC 转换为 tzutc() 时区?
【发布时间】:2019-10-30 12:30:33
【问题描述】:

我有一个简单的时间戳,我需要将其转换为 tzutc() timedate 以计算时间增量。

我使用

将字符串转换为日期
pd.Timestamp(x)

然后使用

将其转换为 UTC
pytz.utc.localize(x)

得到:

Timestamp('2019-01-09 00:00:00+0000', tz='UTC')

问题是我需要比较的日期是

Timestamp('2018-06-07 18:13:53+0000', tz='tzutc()')

当比较它们时,我得到了

TypeError: Timestamp subtraction must have the same timezones or no timezones

【问题讨论】:

标签: python timestamp


【解决方案1】:

您可以使用HERE 中看到的方法将时间戳转换为日期时间并返回。

这是一种使用 pytz 将日期时间从本地时间转换为 UTC 的方法:

def LocalToUTC(dt):
    # Converts the local time to UTC

    localtz = get_localzone()

    if dt.tzinfo is None:
        localdt = localtz.localize(dt)
    else:
        localdt = dt.replace(tzinfo=localtz)

    utcdt = localdt.astimezone(pytz.UTC)
    return utcdt

同样,这里有一种将任何时区转换为 UTC 的方法:

def TimezoneToUTC(dt, timezonestring):
    # Converts from a given timezone to UTC using the timezonestring
    # Example timezone string: 'Europe/Paris' OR 'America/New_York'

    fromtz = pytz.timezone(timezonestring)

    if dt.tzinfo is None:
        localdt = fromtz.localize(dt)
    else:
        localdt = dt.replace(tzinfo=fromtz)

    utcdt = localdt.astimezone(pytz.UTC)
    return utcdt

对于所有时区字符串的列表,请使用:

>>> import pytz
>>> 
>>> for tz in pytz.all_timezones:
...     print tz

【讨论】:

  • 谢谢@iridium237。最终感谢您的链接,我设计了另一个解决方案:我只是将原始日期的时区定义为 tzutc 就像这样: pd.Timestamp(x,tz=tzutc()) 使两个日期戳在同一个时区。跨度>
猜你喜欢
  • 2018-09-03
  • 2011-09-16
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多