【问题标题】:Get new datetime object according to timezone difference根据时区差异获取新的日期时间对象
【发布时间】:2013-05-12 17:46:29
【问题描述】:

这是我的代码

>>>from datetime import datetime
>>>from dateutil import tz
>>>current_time = datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
>>>2013-05-12 17:11:36.362000+05:30

我不想知道偏移量我想将时差添加到我的当前时间 所以时间会是

>>>2013-05-12 22:41:36.362000

这样我就可以简单地得到时差了。

>>> datetime.utcnow() - current_time 

谢谢,

【问题讨论】:

  • 你不需要在每一行之前添加>>>
  • 我会记住这一点的。

标签: python datetime python-2.7


【解决方案1】:

您可以使用datetime.timedelta 获取偏移量:

offset = current_time.utcoffset()

然后可以从 current_time 中添加或减去偏移量以获得所需的日期时间。

import datetime as DT
import dateutil.tz as tz
import dateutil

current_time = DT.datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
print(current_time)
# 2013-05-12 18:33:19.368122+05:30

offset = current_time.utcoffset()
naive_time = current_time.replace(tzinfo=None)
print(naive_time)
# 2013-05-12 18:33:19.368122
print(naive_time + offset)
# 2013-05-13 00:03:19.368122

注意,如果你想要 UTC 时间,你应该减去偏移量:

print(naive_time - offset)
# 2013-05-12 13:03:19.368122

获取 UTC 日期时间的更简单方法是使用 astimezone 方法:

utc = dateutil.tz.tzutc()
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368122+00:00

最后注意使用dateutilreplace设置时区does not always return the correct time。以下是使用pytz 的方法:

import pytz
calcutta = pytz.timezone('Asia/Calcutta')
utc = pytz.utc
current_time = calcutta.localize(DT.datetime.utcnow())
print(current_time)
# 2013-05-12 18:33:19.368705+05:30
print(current_time.astimezone(utc))
# 2013-05-12 13:03:19.368705+00:00

【讨论】:

    【解决方案2】:

    您可以使用datetime.utcoffset()获取偏移量

    current_time = datetime.utcnow().replace(tzinfo=tz.gettz('Asia/Calcutta'))
    td = datetime.utcoffset(current_time)
    #datetime.timedelta(0, 19800)
    td.total_seconds() / 3600
    #5.5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多